<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: joomleague.html.php 1203 2008-07-10 08:20:27Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 *
 * This file is part of JoomLeague.
 *
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
 */

class HTML_joomleague {

  /**
   * displays match results in a table...
   *
   * @param object $matches
   * @param array objects $ResultTeams teams info
   * @param array $config
   */
  function show_matches( &$matchesInfo, &$ResultTeams, &$config ) {
    global $joomleague, $database;
    
    $division = mosGetParam($_REQUEST, 'division', 0);
    
    $favteams=explode(",", $joomleague->fav_team);
    $k=0;
    //$ResultTeams = $joomleague->getTeamsIndexedById(null, $division);    
    
    if ($config['show_dnp_teams'] == 1) {
      $teams_in_league=array();
      foreach ($ResultTeams AS $Ateam) { 
        if ($Ateam->division_id==$division || $Ateam->parent_division_id==$division) {
          $teams_in_league[]=$Ateam;
        }
      }
    }
    
    $olddate = '';
    $playing_teams = array();
    
    foreach($matchesInfo as $matchInfo) {
      $config['class'] = ($k == 0)? $config['style_class1'] : $config['style_class2'];
      
      if ($config['show_dnp_teams'] == 1) {
        $this->addPlayingTeams($playing_teams, $matchInfo->matchpart1, $matchInfo->matchpart2);
      }
      $this->newDayHeading($matchInfo->match_date, $olddate, $config);

      $this->show_match_row( $matchInfo, $ResultTeams, $favteams, $config );
      $k = 1 - $k;
    }
    
    if ($config['show_dnp_teams'] == 1) {
      echo '<tr><td colspan="'.$config['colspan'].'"><div style="text-align:center">';
      $this->show_not_playing_teams($playing_teams, $teams_in_league, $config);
      echo '</div></td></tr>';
    }
  }
  
  /**
   * adds teams in playing teams array if not already present
   *
   * @param array int $playing_teams
   * @param int $hometeam
   * @param int $awayteam
   */
  function addPlayingTeams(&$playing_teams, $hometeam, $awayteam) {
    if ($hometeam > 0 && !in_array($hometeam, $playing_teams)) $playing_teams[]=$hometeam;
    if ($awayteam > 0 && !in_array($awayteam, $playing_teams)) $playing_teams[]=$awayteam;
  }
  
  /**
   * Print new date heading if date changed
   *
   * @param string $newdate
   * @param string $olddate
   * @param array  $config
   */
  function newDayHeading ($newdate, &$olddate, &$config) {
  	list($thisdate, $thistime) = split(" ", $newdate);
  	if($thisdate != $olddate) {
  		$olddate = $thisdate; 
  		?>
			<tr class="sectiontableheader">
				<td	colspan="<?php
				    echo (isset($config['results_below']) && $config['results_below'] == 1) ? 
				      $config['first_colspan'] : ($config['first_colspan'] + $config['second_colspan']);
				  ?>">
				  <?php
					if (!strstr($newdate , "0000-00-00")) echo mosFormatDate($newdate, _JL_MATCHDAYDATE);
					else echo _JL_RESULTS_DATE_TBD;
					?>
				</td>
				<?php
					if (isset($config['results_below']) && $config['results_below'] == 1) {
						$this->newDayHeading_below ($config);
					} 
				?>
			</tr>
	    <?php
    }
  }

  /**
   * print column header for each game part defined in project
   *
   * @param array $config
   */
	function newDayHeading_below (&$config) {
	  global $joomleague;
	  
    if ($config['show_part_results'] == 1){
  	  for ($x=0;$x < $joomleague->game_parts;$x++) { 
  		  ?>
  		  <td style="text-align:right"><?php echo ($x+1).'/'.$joomleague->game_parts;?></td>
  		  <?php
  	  }
    }
	  if ($joomleague->allow_add_time == 1) echo '<td style="text-align:right">'._JL_RESULTS_OVERTIME.'</td>';
	  echo '<td style="text-align:right">'._JL_RESULTS_SCORE.'</td>';
	  if ($joomleague->use_legs == 1) echo '<td style="text-align:right">'._JL_RESULTS_LEGS.'</td>';
	  if ($joomleague->allow_add_time == 1) echo '<td style="text-align:center">&nbsp;</td>';
	  echo '<td colspan="'.$config['second_colspan'].'">&nbsp;</td>';
	}

	/**
	 * Returns match time according to format
	 *
	 * @param object $match
	 * @param object $joomleague
	 * @param array $config
	 * @return string
	 */
	function format_match_time(&$match, &$joomleague, &$config) {
	  global $overall_config;
	  if (!strstr($match->match_date , "0000-00-00 00:00:00")) {
	    
	    if (!isset($overall_config['time_format'])) {
	      $overall_config['time_format'] = "%H:%M";
	    }
	    $shown_time = mosFormatDate($match->match_date, $overall_config['time_format'], 0);
	    if ($config['show_time_suffix']==1) $shown_time .= ' '._JL_CLOCK.'&nbsp;&nbsp;';
	    
	    $config['mark_now_playing']= (isset($config['mark_now_playing'])) ? $config['mark_now_playing'] : 0;
	    
	    if ($config['mark_now_playing']==1) {
	      $thistime=$joomleague->getTimestamp('');
	      $time_to_ellapse = ($joomleague->halftime * ($joomleague->game_parts - 1)) + $joomleague->game_regular_time;
	      if ($joomleague->allow_add_time == 1 && ($match->matchpart1_result == $match->matchpart1_result)) $time_to_ellapse += $joomleague->add_time;
	      $time_to_ellapse = $time_to_ellapse * 60;
	      $match_stamp = $joomleague->getTimestamp($match->match_date, 1);
	      if ($thistime >= $match_stamp && $match_stamp + $time_to_ellapse >= $thistime) {
	        $match_begin = $shown_time.' ';
	        if ($config['show_time_suffix']==1) $match_begin .= _JL_CLOCK;
	        $title = str_replace('%STARTTIME%', $match_begin, trim(htmlspecialchars($config['mark_now_playing_alt_text'])));
	        $title = str_replace('%ACTUALTIME%', $joomleague->mark_now_playing($thistime, $match_stamp, $config), $title);
	        $styletext = '';
	        if (isset($config['mark_now_playing_blink']) && $config['mark_now_playing_blink'] == 1) $styletext = ' style="text-decoration:blink"';
	        $shown_time = '<b><i><acronym title="'.$title.'"'.$styletext.'>'.$config['mark_now_playing_text'].'</acronym></i></b>';
	      }
	    }
	  }
	  else {
	    $shown_time = '-- : --';
	    if ($config['show_time_suffix']==1) $shown_time .= '&nbsp;'._JL_CLOCK;
	  }
	  return $shown_time;
	}
	
	// Open Flash Chart Function START
	function open_flash_chart_object( $width, $height, $url, $ajax=true, $div=0 )
	{
	  if ($ajax) echo '<script type="text/javascript" src="'.JL_URL_FOLDER.'/js/swfobject.js"></script>';
	  $obj_id = 'chart_'.$div;
	  $div_name = 'flashcontent_'.$div;
	  echo '<div id="'. $div_name .'"></div>';
	  echo '<object id="'.$obj_id.'" type="application/x-shockwave-flash" data="'.JL_URL_FOLDER.'/lib/open-flash-chart/open-flash-chart.swf?width='
	  . urlencode($width) .'&height='. $height .'&data=' . $url .'" width="'. urlencode($width) .'" height="'. $height .'">';
	  echo '<param name="movie" value="'.JL_URL_FOLDER.'/lib/open-flash-chart/open-flash-chart.swf?width='
	  . urlencode($width) .'&height='. $height .'&data='. $url .'" />';
	  echo '<param name="allowScriptAccess" value="sameDomain" />';
	  echo '<param name="quality" value="high" />';
	  echo '<param name="bgcolor" value="#FFFFFF" />';
	  echo '<param name="name" value="open-flash-chart" />';
	  echo '<param name="align" value="middle" />';
	  echo '<param name="pluginspage" value="http://www.macromedia.com/go/getflashplayer" />';
	  echo '</object>';
	}
	
	// Open Flash Chart Function END
	function showTitle(&$joomleague, $type=0) {
	  global $database;
	  if ($type == 0) {
	    return $joomleague->name;
	  }
	  else {
	    $output='';
	    $query="SELECT l.name AS lname, l.country, s.name AS sname FROM #__joomleague_leagues AS l,
	       #__joomleague_seasons AS s
	       WHERE l.id = ".$joomleague->league_id." AND s.id = ".$joomleague->season_id;
	    $database->setQuery($query);
	    $league=$database->loadObjectList();
	    $thiscountry = new Country($database);
	    $thiscountry->load($league[0]->country);
	    if ($type == 2) {
	      $flag = $thiscountry->getFlag();
	      $output = $flag.' ';
	    }
	    $output .= $league[0]->lname.' '.$league[0]->sname;
	    return $output;
	  }
	}

	/**
	 * Displays the teams not playing this round
	 *
	 * @param array $playing_teams
	 * @param array $teams_in_league
	 * @param array $results_config
	 */
	function show_not_playing_teams(&$playing_teams, &$teams_in_league, &$config){
		$x=0;
		$not_playing = count($teams_in_league) - count($playing_teams);
		if ( $not_playing > 0 ) {
			echo '<b>'._JL_RESULTS_TEAMS_NOT_PLAYING.'</b> ';
		  foreach ( $teams_in_league AS $id => $team ) {
		  	if ( in_array( $team->team_id, $playing_teams ) ) continue; //if team is playing, go to next
		  	
        if ( $x>0 && $x<$not_playing ) echo ', ';
		  	if ($config['show_logo_small'] > 0) $this->showClubIcon($team, $config['show_logo_small']);
	      echo $this->formatTeamname ($team, 'np',$results_config);
	      $x++;
		  }
	  }
	}
		
	/**
	 * print edit row for game
	 *
	 * @param object match
	 * @param mixed resultTeams
	 * @param int row number
	 * @param array config
	 */
	function editable_row( &$match, &$resultTeams, $i, &$config ) 
	{
	  global $database, $my, $joomleague;
	
	  $thismatch = new Match ($database);
	  $thismatch->bind(get_object_vars($match));
	  	  
	  list($datum, $uhrzeit)=split(" ", $thismatch->match_date);
	  
    $team1 = $resultTeams[$thismatch->matchpart1];
    $team2 = $resultTeams[$thismatch->matchpart2];
    
    $userIsTeamAdmin = ( $my->id == $team1->admin || $my->id == $team2->admin );
    
    $teams = $resultTeams;
	  foreach ($teams AS $team) {
	    $teamsoptions[] = mosHTML::makeOption($team->id, $team->name);
	  }
	  ?>
			<tr class="<?php echo $config['class'];?>">
				<td nowrap="nowrap" valign="top"><?php
				if ($thismatch->checked_out && $thismatch->checked_out != $my->id) {
				  $query="SELECT username FROM #__users WHERE id = $match->checked_out";
				  $joomleague->_db->setQuery($query);
				  $username = $joomleague->_db->loadResult();
				  echo '<acronym title="CHECKED OUT BY '.$username.'">x</acronym>';
				}
				else { ?> <input type="checkbox" id="cb<?php echo $i;?>"
					name="msid[]" value="<?php echo $thismatch->match_id; ?>" /> <a
					href="javascript:void(0)"
					onclick="loadmatchdetails(<?php
						echo $thismatch->match_id.", ".$i;?>);return false;"> <img
					src="<?php echo JL_TEMPLATE_FOLDERS_URL.'/images/edit.png" alt="'
						._JL_EDIT_DETAILS.'" title="'._JL_EDIT_DETAILS.'" border="0" id="edit'.$thismatch->match_id;?>" /></a>
						<?php } ?></td>
						<?php
						if ($config['show_match_number']==1) {
						   ?>
				<td valign="top"><input type="text" class="inputbox" size="2"
					name="match_number<?php echo $thismatch->match_id;?>"
					value="<?php
						echo $thismatch->match_number;?>"
					onchange="document.getElementById('cb<?php echo $i;?>').checked=true;" /></td>
					<?php } ?>
				<td nowrap="nowrap" valign="top">
				  <input type="text" size="8"
					       name="match_date<?php echo $thismatch->match_id;?>"
					       id="match_date<?php echo $thismatch->match_id;?>"
					       value="<?php echo $datum;?>" class="inputbox"
					       onchange="document.getElementById('cb<?php	echo $i;?>').checked=true;" /> 
					<input type="reset" class="inputbox"
					       value="..."
					       onclick="document.getElementById('cb<?php echo $i;?>').checked=true; showCalendar('match_date<?php echo $thismatch->match_id;?>', 'y-mm-dd');" />
	<?php
	if (isset($config['results_below']) && $config['results_below']==1) {?>			<br /><?php }
	else { ?>
	  </td>
				<td align="center" nowrap="nowrap" valign="top">
	<?php } ?>
				<input type="text" size="6"
					name="match_time<?php echo $thismatch->match_id;?>"
					value="<?php
						echo $uhrzeit;?>" class="inputbox"
					onchange="document.getElementById('cb<?php echo $i;?>').checked=true;" /> <?php
					if (isset($config['results_below']) && $config['results_below']==1) echo _JL_CLOCK;?>
				</td>
				<td nowrap="nowrap" valign="top"><?php
				$append='class="inputbox" size="1" onchange="document.getElementById(\'cb'.$i.'\').checked=true;"';
				if (!(defined('JL_USER_IS_PROJECT_ADMIN') || defined('JL_USER_IS_PROJECT_EDITOR')
				|| defined('JL_USER_IS_BIG_BOSS')) && $userIsTeamAdmin ) {
				  $append .= ' disabled="disabled"';
				}
				echo mosHTML::selectList( $teamsoptions, 'matchpart1'.$thismatch->match_id, $append,'value', 'text', $thismatch->matchpart1 );
	      if (isset($config['results_below']) && $config['results_below']==1) {?>			<br /><?php }
	       else { ?>
	        </td>
				<td width="5" valign="top">-</td>
				<td nowrap="nowrap" align="left" valign="top">
	        <?php
	        }
				echo mosHTML::selectList( $teamsoptions, 'matchpart2'.$thismatch->match_id, $append,'value', 'text', $thismatch->matchpart2 );
			?></td>
	<?php
	  if (isset($config['results_below']) && $config['results_below']==1) {
	     $partresults1=explode(";", $thismatch->matchpart1_result_split);
	     $partresults2=explode(";", $thismatch->matchpart2_result_split);
	     for ($x=0;$x<($joomleague->game_parts);$x++) {
	        	?><td align="right"><input type="text" style="font-size:9px;" name="matchpart1_result_split<?php
	          echo $thismatch->match_id;?>[]" value="<?php
	          echo (isset($partresults1[$x])) ? $partresults1[$x] : '';?>" size="2" tabindex="1" class="inputbox" onchange="document.getElementById('cb<?php
	          echo $i;?>').checked=true;" /><br /><input type="text" style="font-size:9px;" name="matchpart2_result_split<?php
	          echo $thismatch->match_id;?>[]" value="<?php
	          echo (isset($partresults2[$x])) ? $partresults2[$x] : '';?>" size="2" tabindex="1" class="inputbox" onchange="document.getElementById('cb<?php
	          echo $i;?>').checked=true;" /></td>
	
	      <?php }
	      if ($joomleague->allow_add_time == 1) {
	?>
	         <td valign="top" align="right">
	         <span id="ot<?php echo $thismatch->match_id;?>">
	         <input type="text" style="font-size:9px;" name="matchpart1_result_ot<?php
	          echo $thismatch->match_id;?>" value="<?php
	          echo (isset($thismatch->matchpart1_result_ot)) ? $thismatch->matchpart1_result_ot : '';?>" size="2" tabindex="1" class="inputbox"
	           onchange="document.getElementById('cb<?php
	          echo $i;?>').checked=true;" /><br /><input type="text" style="font-size:9px;" name="matchpart2_result_ot<?php
	          echo $thismatch->match_id;?>" value="<?php
	          echo (isset($thismatch->matchpart2_result_ot)) ? $thismatch->matchpart2_result_ot : '';?>" size="2" tabindex="1" class="inputbox"
	           onchange="document.getElementById('cb<?php
	          echo $i;?>').checked=true;" /></span></td>
	      <?php }
	      ?>
				<td nowrap="nowrap" valign="top" align="right"><input type="text"
					name="matchpart1_result<?php echo $thismatch->match_id;?>"
					value="<?php echo $thismatch->matchpart1_result;?>" size="2"
					tabindex="1" class="inputbox"
					onchange="document.getElementById('cb<?php echo $i;?>').checked=true;" /><br /><input type="text"
					name="matchpart2_result<?php echo $thismatch->match_id;?>"
					value="<?php echo $thismatch->matchpart2_result;?>" size="2"
					tabindex="1" class="inputbox"
					onchange="document.getElementById('cb<?php echo $i;?>').checked=true;" />
				</td>
	<?php
	  if ($joomleague->use_legs==1) {
	  ?><td valign="top" align="right">
	    <input type="text" style="font-size:9px;" name="matchpart1_legs<?php echo $thismatch->match_id;?>" value="<?php echo $thismatch->matchpart1_legs;
	    ?>" size="2" tabindex="1" class="inputbox" onchange="document.getElementById('cb<?php echo $i;?>').checked=true;" />
	    	<br />
	    	<input type="text" style="font-size:9px;" name="matchpart2_legs<?php echo $thismatch->match_id;?>" value="<?php echo $thismatch->matchpart2_legs;
	    	?>" size="2" tabindex="1" class="inputbox" /></td>
	<?php }
	  } 
	  
	
	else { ?>
	  <td nowrap="nowrap" align="center" valign="top">&nbsp;&nbsp;&nbsp;<input type="text"
					name="matchpart1_result<?php echo $thismatch->match_id;?>"
					value="<?php echo $thismatch->matchpart1_result;?>" size="3"
					tabindex="1" class="inputbox"
					onchange="document.getElementById('cb<?php echo $i;?>').checked=true;" />
				: <input type="text"
					name="matchpart2_result<?php echo $thismatch->match_id;?>"
					value="<?php echo $thismatch->matchpart2_result;?>" size="3"
					tabindex="1" class="inputbox"
					onchange="document.getElementById('cb<?php echo $i;?>').checked=true;" />
					<?php
					$thismatch->editPart_results ($i, $joomleague);?>
		</td>
	<?php }
	/* attention: the type of results is handled in the edit_match.tpl.php */
	  if( $joomleague->allow_add_time ) {
		  echo '<td valign="top">'.
		  HTML_joomleague::getResultTypeSelect( "match_result_type$thismatch->match_id"
		      , 'class="inputbox" size="1" 
		         onchange="document.getElementById(\'cb'.$i.'\').checked=true;"'
		      , $thismatch->match_result_type ).'</td>';
	  }
	  echo '<td colspan="'.$config['second_colspan'].'">&nbsp;</td>';
	?>
			</tr>
				<?php
	}
	
	function PrintIcon( &$row, &$params, $hide_js, $link, $status=NULL ) {
	  global $joomleague, $jl_func, $pid, $tid, $cid, $mid, $pgid, $teamtoolid;
	  $pop = intval(mosGetParam($_REQUEST, 'pop', 0)); //popup for print function
	  $round_id = intval(mosGetParam($_REQUEST, 'r', 0)); //round_id
	  $uid = intval(mosGetParam($_REQUEST, 'uid', 0)); //user_id
	  $event_id=intval(mosGetParam($_REQUEST, "evid",'0')); //event_id
	  if (empty($round)) $round = "";
	  $from = intval(mosGetParam($_REQUEST, 'from', $round));
	  $to = intval(mosGetParam($_REQUEST, 'to', $round));
	  $type = intval(mosGetParam($_REQUEST, 'type', 0));
	  $mode = mosGetParam($_REQUEST, 'mode', '');
	  $params = new mosParameters( '' );
	  $params->def( 'print', true );
	  $params->def( 'popup', false );
	  $params->def( 'icons', true );
	  if ( $params->get( 'print' )  && !$hide_js ) {
	    // use default settings if none declared
	    if ( !$status ) {
	      $status = 'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=640,height=480,directories=no,location=no';
	    }
	
	    // checks template image directory for image, if non found default are loaded
	    if ( $params->get( 'icons' ) ) {
	      $image = mosAdminMenus::ImageCheck( 'printButton.png', '/images/M_images/', NULL, NULL, _CMN_PRINT, _CMN_PRINT );
	    } else {
	      $image = _ICON_SEP .'&nbsp;'. _CMN_PRINT. '&nbsp;'. _ICON_SEP;
	    }
	
	    if ( $pop == '1' && !$hide_js ) {
	      // Print Preview button - used when viewing page
	      ?>
	  <script language="javascript" type="text/javascript">
					<!--
					document.write('<div align="right">');
					document.write('<a href="#" onclick="javascript:window.print(); return false;" title="<?php echo _CMN_PRINT;?>">');
					document.write('<?php echo $image;?>');
					document.write('</a>');
					document.write('</div>');
					//-->
					</script>
					<?php
				} else {
	        if (!empty($uid)) $uid_part = "&amp;uid=$uid"; else $uid_part = "";
	        if (!empty($pid)) $pid_part = "&amp;pid=$pid"; else $pid_part = "";
	        if (!empty($tid)) $tid_part = "&amp;tid=$tid"; else $tid_part = "";
	        if (!empty($teamtoolid)) $ttid_part = "&amp;ttid=$teamtoolid"; else $ttid_part = "";
	        if (!empty($cid)) $cid_part = "&amp;cid=$cid"; else $cid_part = "";
	        if (!empty($round_id)) $round_id_part = "&amp;r=$round_id"; else $round_id_part = "";
	        if (!empty($event_id)) $event_id_part = "&amp;evid=$event_id"; else $event_id_part = "";
	        if (!empty($mid)) $mid_part = "&amp;mid=$mid"; else $mid_part = "";
	        if (!empty($pgid)) $pgid_part = "&amp;pgid=$pgid"; else $pgid_part = "";
	        if (!empty($from)) $from_part = "&amp;from=$from"; else $from_part = "";
	        if (!empty($to)) $to_part = "&amp;to=$to"; else $to_part = "";
	        if (!empty($type)) $type_part = "&amp;type=$type"; else $type_part = "";
	        if (!empty($mode)) $mode_part = "&amp;mode=$mode"; else $mode_part = "";
				  $url = _JOOMLA_JL_LIVE_SITE.'/index2.php?option=com_joomleague&amp;func='.$jl_func.'&amp;p='.$joomleague->id
	        .$uid_part.''.$pid_part.''.$tid_part.''.$ttid_part.''.$round_id_part.''.$cid_part.''.$event_id_part.''.$mid_part.''.$pgid_part.''
	        .$from_part.''.$to_part.''.$type_part.''.$mode_part.JL_ITEMID_SUFFIX.'&amp;pop=1';
					// Print Button - used in pop-up window
					?>
					<div align="right">
						<a href="<?php echo $url; ?>" target="_blank" onclick="window.open('<?php echo $url; ?>','win2','<?php echo $status; ?>'); return false;" title="<?php echo _CMN_PRINT;?>">
							<?php echo $image;?></a>
					</div>
					<div style="clear:left"></div>
					<?php
				}
			}
		}
		
		
	function makeAjaxContainer ($form, $target) {
	  global $mainframe;
	  //$mainframe->addCustomHeadTag( '<script src="'.JL_URL_FOLDER.'/js/mootools.v1.1.js" type="text/javascript" charset="utf-8"></script>' );
	  $output = '<style>
	             .ajax-loading {
	              padding: 20px 0;
	              background: url(';
    $output .= JL_TEMPLATE_FOLDERS_URL.'/images/spinner.gif) no-repeat center;}</style>';
    $mainframe->addCustomHeadTag( $output );
  }
  
	function rankingnav(&$rounds, $type, $from, $to, $divLevel, &$config) {
	  global  $joomleague;
	  $part = intval(mosGetParam($_REQUEST, 'part', 0));
	  $actual_division = intval(mosGetParam($_REQUEST, 'division', 0));
	  $divLevelSelector = '';
	  $conferenceSelector = '';
	  $conSelAppend = '';
	  $divSelAppend = '';
	  $divisionsSelector = '';
	  if ($joomleague->project_type=='DIVISIONS_LEAGUE') {
	    //select division
	    if ( $config['show_project_table'] ) {
	      $divs = array( mosHTML::makeOption( 0, _JL_TABLE_DIVISION_SELECT ) );
	    }
	    $childs = $joomleague->getDivisionsId(1);
	    if (in_array($actual_division, $childs)) $divSelAppend = ' disabled="disabled"';
	    $conferences = array();
	    if ( count($childs) > 0 && $config['show_level1_table']) {
	      $conferences[] = mosHTML::makeOption( 0, _JL_TABLE_DIVISION_LEVEL1 );
	      $divs[]=mosHTML::makeOption( 1, _JL_TABLE_DIVISION_LEVEL1 );
	      foreach ($childs AS $div) {
	        $query = "SELECT name FROM #__joomleague_divisions WHERE id = '".$div."'";
	        $joomleague->_db->setQuery($query);
	        $conferences[] = mosHTML::makeOption( $div, $joomleague->_db->loadResult() );
	      }
	    }
	    $childs = $joomleague->getDivisionsId(2);
	    if (in_array($actual_division, $childs)) $conSelAppend = ' disabled="disabled"';
	    $divisions = array();
	    if ( count($childs) > 0 && $config['show_level2_table']) {
	      $divisions[] = mosHTML::makeOption( 0, _JL_TABLE_DIVISION_LEVEL2 );
	      $divs[]=mosHTML::makeOption( 2, _JL_TABLE_DIVISION_LEVEL2 );
	      foreach ($childs AS $div) {
	        $query = "SELECT name FROM #__joomleague_divisions WHERE id = '".$div."'";
	        $joomleague->_db->setQuery($query);
	        $divisions[] = mosHTML::makeOption( $div, $joomleague->_db->loadResult() );
	      }
	    }
	    //if (count($divs) > 1) $divLevelSelector = mosHTML::selectList( $divs, 'divLevel', 'id="divLevel" class="inputbox" size="1"','value', 'text', $divLevel );
	    $divLevelSelector = '<input type="hidden" id="divLevel" name="divLevel" value="'.$divLevel.'" />';
	    if (count($conferences) > 0) {
	      $conferenceSelector = mosHTML::selectList( $conferences, 'division', 
	        'id="conferences" class="inputbox" size="1" onchange="if (this.selectedIndex!=0) {
	        document.getElementById(\'divLevel\').value=1;document.getElementById(\'divisions\').disabled=true;}else {
	          document.getElementById(\'divisions\').disabled=false;}"'.$conSelAppend,'value', 'text', $actual_division );
	    }
	    else $conferenceSelector = '<input type="hidden" id="conferences" name="division" value="" />';
	    if (count($divisions) > 0) {
	      $divisionsSelector = mosHTML::selectList( $divisions, 'division',
	         'id="divisions" class="inputbox" size="1" onchange="if (this.selectedIndex!=0) {
	         document.getElementById(\'divLevel\').value=2;document.getElementById(\'conferences\').disabled=true;}else {
	          document.getElementById(\'conferences\').disabled=false;}"'.$divSelAppend,'value', 'text', $actual_division );
	    }
	    else $divisionsSelector = '<input type="hidden" id="divisions" name="division" value="" />';
	  
	    if ($divLevel == 1) {
	      //$divisionsSelector = '<div id="divisions'.$divLevel.'" style="display:none">'.$divisionsSelector.'</div>';
	    }
	    elseif ($divLevel == 2) {
	     // $conferenceSelector = '<div id="divisions'.$divLevel.'" style="display:none">'.$conferenceSelector.'</div>';
	    }
	  }
	  
	  
	  $partselector='<input type="hidden" id="part" name="part" value="0" />';
	  //select ranking type
	  $rankingtypes=array(_JL_TABLE_ALL => sefRelToAbs(JL_COMPONENT_LINK."&func=showRanking&p=".$joomleague->id.JL_ITEMID_SUFFIX),
	    _JL_TABLE_HOME => sefRelToAbs(JL_COMPONENT_LINK."&func=showRanking&p=".$joomleague->id.'&amp;type=1'.JL_ITEMID_SUFFIX),
	    _JL_TABLE_AWAY => sefRelToAbs(JL_COMPONENT_LINK."&func=showRanking&p=".$joomleague->id.'&amp;type=2'.JL_ITEMID_SUFFIX));
	  
	  if ($config['show_triple_ranking'] == 1) $rankingtypes[_JL_TABLE_TRIPLE] = sefRelToAbs(JL_COMPONENT_LINK
	    ."&func=showRanking&p=".$joomleague->id.'&amp;type=3'.JL_ITEMID_SUFFIX);
	  foreach ($rankingtypes AS $key => $value) {
	    $rankingtypeoptions[] = mosHTML::makeOption( $value, "$key" );
	  }
	  $typeselector = mosHTML::selectList( $rankingtypeoptions, 'rankingtype', ' id="rankingtype" class="inputbox" size="1"','value', 'text', sefRelToAbs(JL_COMPONENT_LINK."&func=showRanking&p=".$joomleague->id.'&amp;type='.$type.JL_ITEMID_SUFFIX) );
	
	  //select season part (if number of rounds is even)
	  $parts=intval(count($rounds)/2);
	  if ($parts==count($rounds)/2) {
	    $rankingparts=array(_JL_TABLE_MDAY_SELECT." ->" => 0,
	      _JL_TABLE_1STROUND => 1,
	      _JL_TABLE_2NDROUND => 2);
	    foreach ($rankingparts AS $key => $value) {
	      $rankingpartoptions[] = mosHTML::makeOption( $value, "$key" );
	    }
	
	    $partselector = mosHTML::selectList( $rankingpartoptions, 'part', 'id="part" class="inputbox" size="1" onchange="if (this.selectedIndex==0) { document.getElementById(\'from\').disabled=false;document.getElementById(\'to\').disabled=false } else { document.getElementById(\'from\').disabled=true;document.getElementById(\'to\').disabled=true }"','value', 'text', $part );
	  }
	
	  // select start and end rounds
	  foreach ($rounds AS $key => $value) {
	    if ($config['type_section_heading'] == 1)
	      $name = $value->name;
	    else
	      $name = $value->matchcode . " "._JL_MATCHDAY;
	   
	    $fromtooptions[] = mosHTML::makeOption( $value->matchcode, "$name" );
	  }
	  $from_to_append = '';
	  if ($part>0) $from_to_append = ' disabled="disabled"';
	  $fromselector = mosHTML::selectList( $fromtooptions, 'from', 'id="from" class="inputbox" size="1"'.$from_to_append,'value', 'text', $from );
	  $toselector = mosHTML::selectList( $fromtooptions, 'to', 'id="to" class="inputbox" size="1"'.$from_to_append,'value', 'text', $to );
	
	  return $typeselector.'<form action="'.sefRelToAbs(JL_COMPONENT_LINK."&func=showRanking&p=".$joomleague->id.JL_ITEMID_SUFFIX)
	   .'" method="post" style="display:inline">'.$divLevelSelector.$conferenceSelector.$divisionsSelector.$partselector._JL_TABLE_FROM.$fromselector._JL_TABLE_TO.$toselector
	   .'<input type="button" value="'._JL_CHANGE
	   .'" class="inputbox" onclick="this.form.action=document.getElementById(\'rankingtype\').value;this.form.submit()" />
	   <input type="hidden" name="sef" value="1" /></form>';
	}

	function tiprankingnav(&$rounds, $from, $to, &$config, &$table_config) {
	  global  $joomleague;
      if (mosGetParam($_REQUEST, 'part', '')!='') {
        $part=intval(mosGetParam($_REQUEST, 'part', 0));
      } else {
        if ($joomleague->overview==0) $part=0; else if ($to > intval(count($rounds)/2)) $part=2; else $part=1;
      }
      $partselector='<input type="hidden" id="part" name="part" value="0" />';
	  //select season part (if number of rounds is even)
	  $parts=intval(count($rounds)/2);
	  if ($parts==count($rounds)/2) {
	    $rankingparts=array(_JL_TABLE_MDAY_SELECT." ->" => 0,
	      _JL_TABLE_1STROUND => 1,
	      _JL_TABLE_2NDROUND => 2);
	    foreach ($rankingparts AS $key => $value) {
	      $rankingpartoptions[] = mosHTML::makeOption( $value, "$key" );
	    }
	
	    $partselector = mosHTML::selectList( $rankingpartoptions, 'part', 'id="part" class="inputbox" size="1" onchange="if (this.selectedIndex==0) { document.getElementById(\'from\').disabled=false;document.getElementById(\'to\').disabled=false } else { document.getElementById(\'from\').disabled=true;document.getElementById(\'to\').disabled=true }"','value', 'text', $part );
	  }
	
	  // select start and end rounds
	  foreach ($rounds AS $key => $value) {
	    if ($table_config['type_section_heading'] == 1)
	      $name = $value->name;
	    else
	      $name = $value->matchcode . " "._JL_MATCHDAY;
	   
	    $fromtooptions[] = mosHTML::makeOption( $value->matchcode, "$name" );
	  }
	  $from_to_append = '';
	  if ($part>0) $from_to_append = ' disabled="disabled"';
	  $fromselector = mosHTML::selectList( $fromtooptions, 'from', 'id="from" class="inputbox" size="1"'.$from_to_append,'value', 'text', $from );
	  $toselector = mosHTML::selectList( $fromtooptions, 'to', 'id="to" class="inputbox" size="1"'.$from_to_append,'value', 'text', $to );
	
	  return '<form action="'.sefRelToAbs(JL_COMPONENT_LINK."&func=showTipRanking&mode=all&p=".$joomleague->id.JL_ITEMID_SUFFIX)
	   .'" method="post" style="display:inline">'.$partselector._JL_TABLE_FROM.$fromselector._JL_TABLE_TO.$toselector
	   .'<input type="button" value="'._JL_CHANGE
	   .'" class="inputbox" onclick="this.form.action=this.form.submit()" />
	   <input type="hidden" name="sef" value="1" /></form>';
	}
	
	function show_ranking_title (&$config) {
	  //global $rounds, $joomleague, $from, $to, $type, $current_round;
	  //		$titles=array(_JL_TABLE_ALL, _JL_TABLE_HOME, _JL_TABLE_AWAY);
	  //		$titlesadd=array("", _JL_TABLE_1STROUND, _JL_TABLE_2NDROUND);
	  //		$title =$titles[$type].$titlesadd[$part];
	  //		echo $title;
	  //		if ($from==1&&$to==count($rounds)/2) echo " "._JL_TABLE_1STROUND;
	  //		elseif ($from==(count($rounds)/2+1)&&$to==count($rounds)) echo " "._JL_TABLE_2NDROUND;
	  //		elseif ($from>0) {
	  //			if ($config[type_section_heading]==1&&$rounds[$from]->name!="") {
	  //				echo $rounds[$from-1]->name." - ".$rounds[$to-1]->name;
	  //			}
	  //			else echo $from.".  - ".$to.". "._JL_MATCHDAY;
	  //	}
	  echo _JL_PAGE_TITLE_RANKING;
	}

	/**
	 * Print matchday as title
	 *
	 * @param string $title
	 * @param int $current_round
	 * @param array $config
	 * @param int $mode
	 * @param string $OnlyOneStarttime
	 */
	function show_matchdays_title( $title, $current_round, &$config, $mode=0, $OnlyOneStarttime="" ) 
	{
	  global $joomleague, $database;
	
	  echo ($title != '') ? $title.' - ' : $title;
	  
	  if ($current_round > 0) 
	  {
	    $thisround= new Round ( $database );
	    $thisround->load ( $current_round );
	    
	    if ( $config['type_section_heading'] == 1 && $thisround->name != "" ) 
	    {
	      if ( $mode==1 ) 
	      {
          // create a link to results & ranking for project
	      	echo '<a href="'.
	             sefRelToAbs( JL_COMPONENT_LINK
	                 . "&amp;func=showResultsRank" 
	                 . "&amp;p=".$joomleague->id
	                 . JL_ITEMID_SUFFIX
	                 . "&amp;r=".$thisround->matchcode )
	             .'">';
	      }
	      echo $thisround->name;
	      if ( $mode==1 ) {
	       echo '</a>';
	      }
	    }
	    else if ($thisround->matchcode>0) {
	      echo ' - '.$thisround->matchcode.'. '._JL_MATCHDAY.'&nbsp;';
	    }
	    
	    if ( $config['show_rounds_dates'] == 1 ) 
	    {
	      echo " (";
	      if ( ! strstr( $thisround->round_date_first , "0000-00-00" ) ) 
	      {
	        echo mosFormatDate( $thisround->round_date_first." 00:00:00", 
	                            _JL_BASIC_CALENDAR_DATE, 
	                            0);
	      }
	      if ( ( $thisround->round_date_last != $thisround->round_date_first )
	          && ! strstr( $thisround->round_date_last , "0000-00-00" ) ) {
	        echo " - ".mosFormatDate($thisround->round_date_last." 00:00:00", _JL_BASIC_CALENDAR_DATE, 0).")";
	      }
	      else echo ")";
	    }
	  }
	}

	
	function show_team_icons (&$teamInfo, &$config, $project = 0)
	{
	  global $joomleague, $team_plan, $database;
	  $teamtoolid = $teamInfo->teamtoolid;
	  $teamname = $teamInfo->name;
	  $teamid = $teamInfo->id;
	  $division_id = $teamInfo->division_id;
	  $clubid = $teamInfo->club_id;
	  $projectId = ( $project > 0 ? $project : $teamInfo->project_id );
	  $output = '';
	  
	  if ($config['show_team_link']==1) {
	    $output .= '          	<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showPlayers&amp;p='.$projectId.'&amp;ttid='.$teamtoolid.JL_ITEMID_SUFFIX).'">
				<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/team_icon.png" border="0" alt="'._JL_PAGE_TITLE_PLAYERS.'&nbsp;'.$teamname.'" title="'._JL_PAGE_TITLE_PLAYERS.'&nbsp;'.$teamname.'" /></a>&nbsp;';
	  }
	  if ((!isset($team_plan)||$teamid!=$team_plan->id)&&$config['show_plan_link']==1) {
	    $output .= '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showPlan&amp;p='.$projectId.'&amp;tid='.$teamid.JL_ITEMID_SUFFIX).'">
				<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/calendar_icon.gif" border="0" alt="'._JL_PLAN.'&nbsp;'.$teamname.'" title="'._JL_PLAN.'&nbsp;'.$teamname.'" /></a>&nbsp; ';
	  }
	  if ($config['show_curve_link']==1) {
	    $div_anchor = ($division_id > 0) ? '#division'.$division_id :'';
	    $output .= '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showCurve&amp;p='.$projectId.'&amp;tid='
	    .$teamid.'&amp;division='.$division_id.JL_ITEMID_SUFFIX).'">
				<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/curve_icon.gif" border="0" alt="'._JL_CURVE.'&nbsp;'.$teamname.'" title="'._JL_CURVE.'&nbsp;'.$teamname.'" /></a>&nbsp;';
	  }
	  if ($config['show_teaminfo_link']==1) {
	    $output .= '          	<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showTeamInfo&amp;p='.$projectId.'&amp;tid='.$teamid.JL_ITEMID_SUFFIX).'">
				<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/teaminfo_icon.png" border="0" alt="'._JL_PAGE_TITLE_TEAMINFO.'&nbsp;'.$teamname.'" title="'._JL_PAGE_TITLE_TEAMINFO.'&nbsp;'.$teamname.'" /></a>&nbsp;';
	  }
	  if ($config['show_club_link']==1) {
	    $output .= '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showClubInfo&amp;p='.$projectId.'&amp;cid='.$clubid.JL_ITEMID_SUFFIX).'">
				<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/mail.gif" border="0" alt="'._JL_PAGE_TITLE_CLUB_INFO.'&nbsp;'.$teamname
	    .'" title="'._JL_PAGE_TITLE_CLUB_INFO.'&nbsp;'.$teamname.'" /></a>';
	  }
	  return $output;
	}


// function for walking through pages, only used in eventsstats yet
function next_last_pages ($url, $text, $maxentries, $limitstart=0, $limit=10) {
  $latestlimitstart = (intval($limitstart - $limit) > 0) ? intval($limitstart - $limit) : 0;
  $nextlimitstart = (($limitstart + $limit) < $maxentries) ? $limitstart + $limit : 0;
  $lastlimitstart = ($maxentries%$limit == 0) ? ($maxentries - ($maxentries%$limit) - $limit) : ($maxentries - ($maxentries%$limit));
  ?>
<center>
<table style="width: 50%; align: center;" cellspacing="0"
	cellpadding="0" border="0">
	<tr>
		<td style="width: 10%; text-align: left;" nowrap="nowrap"><?php if ($limitstart > 0) { ?>
		<a
			href=" <?php echo sefRelToAbs($url.'&amp;limit='.$limit.'&amp;limitstart=0');?>">&lt;&lt;&lt;</a>&nbsp;&nbsp;&nbsp;
		<a
			href=" <?php echo sefRelToAbs($url.'&amp;limit='.$limit.'&amp;limitstart='.$latestlimitstart);
			?>"> &lt;&lt;</a> <?php
}?></td>
		<td style="text-align: center;" nowrap="nowrap"><?php 
		$players_to =(($limitstart+$limit)<$maxentries)?($limitstart+$limit):$maxentries;
		echo sprintf($text, $maxentries,($limitstart+1).' - '.$players_to); ?>
		</td>
		<td style="width: 10%; text-align: right;" nowrap="nowrap"><?php if ($nextlimitstart > 0) { ?>
		&nbsp;&nbsp;&nbsp; <a
			href=" <?php echo sefRelToAbs($url.'&amp;limit='.$limit.'&amp;limitstart='.$nextlimitstart);
?>"> &gt;&gt;</a> &nbsp;&nbsp;&nbsp; <a
			href=" <?php echo sefRelToAbs($url.'&amp;limit='.$limit.'&amp;limitstart='.$lastlimitstart);?>">&gt;&gt;&gt;</a>
			<?php
}
?></td>
	</tr>
</table>
</center>
<?php
}
// new function for walking through pages, only used in eventsstats yet ENDS
// ===================================================================================000
// show_event_stats changed for now less information coming from getEventsRanking() in JoomLeague.class.php
// player's and team's information are no more available before called
// page navigation is shown below
function show_event_stats( &$eventtypes, &$eventranking, &$config, $limit = 5, $limitstart = 0 ) 
{
  global $joomleague, $database;

  $countevent=0;
  foreach ($eventtypes AS $rows) 
  {
    if ( count($eventranking[$rows->id]) ) 
    {
      // calculate the total number of rows for this ranking.
    	$totalplayers = count( $joomleague->getEventsRanking( $rows->id, $rows->splitt ) );
      
    	$colspan=8;
      $countevent++;
      if (count($eventtypes)>1) {
	      ?>
	      <table width="100%" class="contentpaneopen">
	       <tr>
	          <td class="contentheading"><?php echo $rows->name; ?></td>
	        </tr>
	      </table>
	      <?php
      }
      ?>
		  <table width="100%" align="center" border="0" cellpadding="3" cellspacing="0">
		  <tr class="sectiontableheader">
		    <td class="sectiontableheader" width="20">&nbsp;</td>
		    <td class="sectiontableheader" width="25"><?php echo _JL_TABLE_POSITION; ?></td>
		    <?php if($config['show_picture_thumb']==1) { echo '<td class="sectiontableheader">&nbsp;</td>';$colspan++;} ?>
		    <td class="sectiontableheader"><?php echo _CMN_NAME; ?></td>
		    <?php if($config['show_nation']==1) { echo '<td class="sectiontableheader"  width="50">&nbsp;</td>';$colspan++;}?>
		    <td class="sectiontableheader"><?php echo _JL_TABLE_TEAM; ?></td>
		    <td class="sectiontableheader" width="20"<?php if ($rows->splitt==0) echo ' colspan="2"';?>>&nbsp;</td>
		        <?php if ($rows->splitt==1) { echo '<td class="sectiontableheader" width="90" style="text-align: center">'.$rows->name.'</td>';}?>
		    <td class="sectiontableheader" style="text-align: right"
		      nowrap="nowrap"><?php
		      if ( $config['show_icons'] == 1 
		        && file_exists(_JOOMLA_JL_PATH.'/images/joomleague/event_icons/'.$rows->icon) ) 
		      {
		        echo '<img src="'._JOOMLA_JL_PATH.'/images/joomleague/event_icons/'.$rows->icon.'" alt="'.$rows->name.'" title="'.$rows->name.'" align="top" hspace="2" />';
		      }
		      ?> <a href="<?php
		              echo sefRelToAbs(JL_COMPONENT_LINK."&amp;func=eventsStats&amp;p=".$joomleague->id."&amp;evid=".$rows->id.JL_ITEMID_SUFFIX);
		                  ?>"><?php echo _JL_STATS_QUANTITY;?></a>
		    </td>
		    <td class="sectiontableheader" width="20">&nbsp;</td>
		  </tr>
		  <?php
		  $k = 0;
		  $lastscores=0;
		  $lastrank=0;

		  // TODO: to be optimized... 3 requests per row here, one for playertool,
		  // one for player, one for team !!!
		  foreach( $eventranking[$rows->id] as $row )
		  {
		    $playertool = new PlayerTool($database);
		    $playertool->load($row->player_id);
		    if(is_a($playertool,'Playertool')){
		      $team = new JL_Team( $database );
		      $team->load($playertool->team_id);
		      $player = new Player($database);
		      $player->load($playertool->player_id);
		    }
		    if ($row->player_id2!=0) {
		     $playertool2 = new PlayerTool($database);
		     $playertool2->load($row->player_id2);
		     if(is_a($playertool2,'Playertool')){
		      $player2 = new Player($database);
		      $player2->load($playertool2->player_id);
		     }
		    }
		    if ($lastrank==$row->rank) {
		      $platzausgabe ='';
		    }
		    else {
		      $platzausgabe=$row->rank;
		      $k = 1 - $k;
		    }
        $class = ($k == 0)? $config['style_class1'] : $config['style_class2'];
        ?>
  <tr class="<?php print $class;?>">
    <td width="20">&nbsp;</td>
    <td style="text-align: right;"><b><?php echo $platzausgabe; ?></b></td>
    <?php
    if($config['show_picture_thumb']==1) {
        echo '<td>';
        $picture = ($playertool->picture!=''&&!is_null($playertool->picture)&&file_exists(_JOOMLA_JL_PATH.'/'.$playertool->picture)) ? $playertool->picture : $player->default_picture;
        if ($picture!=''&&!is_null($picture)&&file_exists(_JOOMLA_JL_PATH.'/'.$picture)) {
          $Thumb = new PowerThumb();
          $Thumb->setSrc($picture);
          $Thumb->setDescription($playertool->description);
          $Thumb->setAlt($player->firstname." ".$player->lastname);
          $Thumb->setMaxHeight(30);
          $Thumb->setAmpliationLink(false);
          $Thumb->create();
        }
        echo '</td>';
    }
    ?>
    <td width="30%" nowrap="nowrap"><?php
    if($config['link_to_player']==1) {
        echo '<a href="'.sefRelToAbs(JL_COMPONENT_LINK."&amp;func=showPlayer&amp;p=".$joomleague->id."&amp;pid=".$playertool->player_id.JL_ITEMID_SUFFIX).'">';
    }
    echo $player->lastname;
    if ($player->firstname!='') echo ", ".$player->firstname;
    if($config['link_to_player']==1) { echo "</a>"; }

        if ($row->player_id2!=0) {
      echo ' / ';
          if($config['link_to_player']==1) {
        echo '<a href="'.sefRelToAbs(JL_COMPONENT_LINK."&amp;func=showPlayer&amp;p=".$joomleague->id."&amp;pid=".$playertool2->player_id.JL_ITEMID_SUFFIX).'">';
      }
      echo $player2->lastname;
      if ($player2->firstname!='') echo ", ".$player2->firstname;
      if($config['link_to_player']==1) { echo "</a>"; }
    }

    echo '</td>';
    if($config['show_nation']==1) {
      echo '<td nowrap="nowrap">';
      $query="SELECT * FROM #__joomleague_countries WHERE countries_id = ".$player->nation;
      $database->setQuery($query);
      if ($countries = $database->loadObjectList()) {
        if (file_exists(_JOOMLA_JL_PATH."/images/joomleague/flags/".strtolower($countries[0]->countries_iso_code_2).".png")) {
          echo "<img src=\""._JOOMLA_JL_LIVE_SITE."/images/joomleague/flags/".strtolower($countries[0]->countries_iso_code_2).".png\" alt=\"".$countries[0]->countries_iso_code_3."\" title=\"".$countries[0]->countries_iso_code_3."\" hspace=\"2\" /> ";
        }
        else echo " [".$countries[0]->countries_iso_code_3."]";
      }
          if ($row->player_id2!=0) {
          $query="SELECT * FROM #__joomleague_countries WHERE countries_id = ".$player2->nation;
            $database->setQuery($query);
          if ($countries = $database->loadObjectList()) {
              if (file_exists(_JOOMLA_JL_PATH."/images/joomleague/flags/".strtolower($countries[0]->countries_iso_code_2).".png")) {
                  echo " / <img src=\""._JOOMLA_JL_LIVE_SITE."/images/joomleague/flags/".strtolower($countries[0]->countries_iso_code_2).".png\" alt=\"".$countries[0]->countries_iso_code_3."\" title=\"".$countries[0]->countries_iso_code_3."\" hspace=\"2\" /> ";
              }
              else echo " / [".$countries[0]->countries_iso_code_3."]";
          }
      }
      echo '</td>';
    }
    ?>
    
    
    <td width="30%"><?php
    if($config['link_to_team']==1) {
      echo '<a href="'.sefRelToAbs(JL_COMPONENT_LINK."&amp;func=showPlayers&amp;p=".$joomleague->id."&amp;ttid="
      .$joomleague->getTeamtool_id($team->id).JL_ITEMID_SUFFIX).'">';
    }
    echo $team->name;
    if($config['link_to_team']==1) { echo "</a>"; }
    ?></td>
    <td width="20"<?php if ($rows->splitt==0) echo ' colspan="2"';?>>&nbsp;</td>
    <?php if ($rows->splitt==1) { echo '<td width="90" style="text-align: center">'; echo (is_numeric($row->notice)) ? intval($row->notice) : $row->notice; echo '</td>'; }?>
      <td style="text-align: right"><b><?php echo $row->p;?></b></td>
    <td width="20">&nbsp;</td>
  </tr>
  <?php
  $lastrank=$row->rank;
}
?>
  </table>
<?php
if ( count($eventtypes)>1 ) {
  if ( $totalplayers > $limit ) { ?>
    <div align="right">
      <a href="<?php echo sefRelToAbs(JL_COMPONENT_LINK."&amp;func=eventsStats&amp;p=".$joomleague->id."&amp;evid=".$rows->id.JL_ITEMID_SUFFIX);
      ?>"><?php echo _JL_MORE;?></a>
  </div>
  <?php
  }
  else if ( count($eventtypes) > $countevent ) {
    ?>
    <br />
      <?php
    }
}
else if ( $totalplayers > $limit ) {
  $url = JL_COMPONENT_LINK.'&amp;func=eventsStats&amp;p='.$joomleague->id.'&amp;evid='.$rows->id.JL_ITEMID_SUFFIX;
  ?>
  <table width="100%" align="center" border="0" cellpadding="3" cellspacing="0">
    <tr>
    <td colspan="<?php echo $colspan;?>" style="text-align: center;"><br />
    <?php
    $this->next_last_pages( $url, _JL_TOTAL.':  %s ('._JL_DISPLAYED_NUMBERS.' %s)', $totalplayers, $limitstart, $limit);
    ?></td>
  </tr>
  </table>
  <?php
  }
  }
 }
}
// ENDE
// ###########################################################################
//
// ###########################################################################
// ANFANG
function init_ranking(&$config) {
  global $joomleague;
  $colspan=5;
  if ($joomleague->use_legs==1){
    $colspan++;
    if($config['show_legs_diff']==1) $colspan++;
  }
  if($config['show_cnt_matches']==1) $colspan++;
  if($config['show_won']==1)  $colspan++;
  if($config['show_draw']==1) $colspan++;
  if($config['show_lost']==1) $colspan++;
  if($config['show_results']==1) $colspan++;
  if($config['show_diff']==1) $colspan++;
  if($config['show_points']==1) $colspan++;
  return $colspan;
}
//
// ###############################################################################################
//
// ###############################################################################################
// ANFANG
function show_manipulations ($teams) 
{
  $found = false;
  $count = 0;
	foreach($teams as $r) 
	{
    if(trim($r->info) != "") 
    {
    	if ( !$found )
    	{ ?>
        <table id="jl_startpointslegend" width="96%" align="center" border="0" cellpadding="3" cellspacing="0">
        <thead>
        <tr>
          <td class="sectiontableheader"><?php echo _JL_TABLE_POINTS_MANIPULATION;?></td>
        </tr>
        </thead>
        <tbody>
        <?php
        $found = true;
			}
			?>
			<tr>
			<td class="sectiontableentry<?php echo $count % 2; ?>"><?php print $r->info;?></td>
			</tr>
		  <?php
		  $count++;
    }
	}
	if ( $found ) { ?>
    </tbody>
    </table>
	<?php
  }
}
// ENDE
// ###############################################################################################
//
// ###############################################################################################
// ANFANG Anzeige der Farblegende
/**
 * displays color legend
 * @param array the formatted colors array (color, description)
 */
function show_colors_legend( $colors ) {
  global $joomleague;
    
  $favshow = mosGetParam($_REQUEST, 'func', '');
  if ($favshow != 'showCurve' && $joomleague->fav_team ) {
    $fav = array("color"=>$joomleague->fav_team_color,"description"=>_JL_TABLE_FAVTEAM);
    array_push($colors, $fav);
  }
  
  if (!count($colors)) return;
  
  foreach($colors as $color) {
    if(trim($color["description"]) != "")
    print '<td align="center" bgcolor="'.$color["color"].'"><b>'.$color["description"].'</b>&nbsp;</td>';
  }
}
// ENDE Anzeige der Farblegende
// ###############################################################################################
//
// ###############################################################################################

/**
 * callback functions for ranking table sorting.
 **/
function teamNameCmp( &$a, &$b){
  return strcasecmp ($a->team->name, $b->team->name);
}

function wonCmp( &$a, &$b){
  $res = $a->cnt_won - $b->cnt_won;
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function drawCmp( &$a, &$b){
  $res = ($a->cnt_draw - $b->cnt_draw);
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function lossCmp( &$a, &$b){
  $res = ($a->cnt_lost - $b->cnt_lost);
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function winpctCmp( &$a, &$b){
  $pct_a = $a->cnt_won/($a->cnt_won+$a->cnt_lost+$a->cnt_draw);
  $pct_b = $b->cnt_won/($b->cnt_won+$b->cnt_lost+$b->cnt_draw);
  $res =($pct_a < $pct_b);
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function goalspCmp( &$a, &$b){
  $res = ($a->sum_matchpart1_result - $b->sum_matchpart1_result);
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function diffCmp( &$a, &$b){
  $res = ($a->diff_matchpart_results - $b->diff_matchpart_results);
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function pointsCmp( &$a, &$b){
  $res = ($a->sum_points - $b->sum_points);
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function bonusCmp( &$a, &$b){
  $res = ($a->bonus_points - $b->bonus_points);
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function startCmp( &$a, &$b){
  $res = ($a->team->start_points * $b->team->start_points);
  //if (!$res) $res = $this->teamNameCmp( $a, $b);
  return $res;
}

function teamNameCmp2( &$a, &$b){
  return strcasecmp ($a->team, $b->team);
}

function totalattendCmp( &$a, &$b){
  $res = ($a->sumspectatorspt - $b->sumspectatorspt);
  return $res;
}

function avgattendCmp( &$a, &$b){
  $res = ($a->avgspectatorspt - $b->avgspectatorspt);
  return $res;
}

function capacityCmp( &$a, &$b){
  $res = ($a->capacity - $b->capacity);
  return $res;
}

function utilisationCmp( &$a, &$b){
  $res = (($a->capacity?($a->avgspectatorspt / $a->capacity):0) - ($b->capacity>0?($b->avgspectatorspt / $b->capacity):0));
  return $res;
}

/**
 * display ranking rows
 *
 * @param mixed $a current ranking
 * @param mixed $b previous ranking
 * @param mixed $homeRank home ranking
 * @param mixed $awayRank avway ranking
 * @param int $type type of ranking (normal, home, away, triple)
 * @param mixed $config
 */
function show_ranking_entries(&$a, &$b, $homeRank, $awayRank, $type, &$config) 
{
  global $joomleague, $database;
  
  // columns to display
  $columns = explode( ",", $config['ordered_columns'] );
  
  $counter=1;
  $k = 0;
  $j = 0;
  $temprank=0;
  $tempoldrank=0;
  $colors = $joomleague->getColors($config['colors']);
  //print_r($colors);
  $current_round = intval( mosGetParam( $_REQUEST, 'r', $joomleague->current_round ) );
  $favteam=explode(",", $joomleague->fav_team);
  
  if (isset($_REQUEST['order'])) 
  {
    //reorder table according to criteria
    switch ($_REQUEST['order']) 
    {
      case 'name':
        uasort( $a, array("HTML_joomleague","teamNameCmp" ));
        break;
      case 'rank':
        break;
      case 'won':
        uasort( $a, array("HTML_joomleague","wonCmp" ));
        break;
      case 'draw':
        uasort( $a, array("HTML_joomleague","drawCmp" ));
        break;
      case 'loss':
        uasort( $a, array("HTML_joomleague","lossCmp" ));
        break;
      case 'winpct':
        uasort( $a, array("HTML_joomleague","winpctCmp" ));
        break;
      case 'goalsp':
        uasort( $a, array("HTML_joomleague","goalspCmp" ));
        break;
      case 'diff':
        uasort( $a, array("HTML_joomleague","diffCmp" ));
        break;
      case 'points':
        uasort( $a, array("HTML_joomleague","pointsCmp" ));
        break;
      case 'start':
        uasort( $a, array("HTML_joomleague","startCmp" ));
        break;
      case 'bonus':
        uasort( $a, array("HTML_joomleague","bonusCmp" ));
        break;
    }
    if ($_REQUEST['dir']=='DESC') $a=array_reverse($a, true);
  }

  foreach( $a as $akey => $aval )
  {  
    $class = ($k == 0)? $config['style_class1'] : $config['style_class2'];

    $color = "";
    if(isset($colors[$j]["from"]) && $counter == $colors[$j]["from"]) $color = $colors[$j]["color"];

    if(isset($colors[$j]["from"]) && isset($colors[$j]["to"])&&($counter > $colors[$j]["from"] && $counter <= $colors[$j]["to"])) $color = $colors[$j]["color"];
    if(isset($colors[$j]["to"]) && $counter == $colors[$j]["to"]) $j++;

    $format = "%s";

    if(in_array($aval->team->id, $favteam) && $config['fav_highlight_type']==1)
    {       
      if(trim($joomleague->fav_team_color) != "") $color = $joomleague->fav_team_color;
      $format = "%s";
    }

    //GB calculation, store wins and loss count of the team in first place
    if ($aval->rank == 1 )
    {
      $ref_won = $aval->cnt_won;
      $ref_lost = $aval->cnt_lost;
    }

    ?>
    <tr class="<?php echo $class;?>">
			<td valign="top"
        <?php 
        if ( $color != '' ) { 
          echo ' style="background-color: '.$color.'"'; 
        }
        ?> align="right" nowrap="nowrap">
        <?php
				if ($aval->rank!=$temprank) {
				  printf($format, $aval->rank);
				}
				else {
				  echo "-";
				}
				//printf($format, $counter);
				?>
			</td>
		
			<td valign="top"
			<?php 
			if ( $color != '' ) { 
        echo " style='background-color: ".$color."'"; 
			}
			?>>
				<?php
				if ( isset( $b[$akey]->rank ) ) 
				{
				  echo '<img align="middle" src="'.JL_TEMPLATE_FOLDERS_URL.'/images/';
				  if ( $aval->rank == $b[$akey]->rank || $b[$akey]->rank == "" ) {
				  	echo "same";
				  }
				  else if ( $aval->rank < $b [$akey]->rank ) echo "up";
				  else if ( $aval->rank > $b[$akey]->rank ) echo "down";
				  echo '.png" alt="" title="" />';
				}
				echo '</td><td valign="top" nowrap="nowrap" style="background-color:'
				     .$color.'" align="right">';
				echo '<span class="small">';
				print ($config['last_ranking']==1 && isset($b[$akey]->rank)) ? sprintf("(%s)",$b[$akey]->rank) : '';
				echo '</span>';
				?>
			</td>
			<?php
			if ( $config['show_logo_small_table'] > 0 ) 
			{ 
		    ?>
				<td valign="top"
				<?php if($color!='') { echo ' style="background-color: '.$color.'"'; }?>
					align="center"><?php 
					$this->showClubIcon($aval->team, $config['show_logo_small_table']);?>
				</td>
				<?php
			}
			?>
			<td valign="top" nowrap="nowrap"
				<?php 
				if($color!='') { 
				 echo ' style="background-color: '.$color.'"'; 
				}
				?>
					align="left">
				<?php	
				$config['highlight_fav'] = in_array($aval->team->id, $favteam) ? 1 : 0;
				echo $this->formatTeamname ($aval->team, 't'.$aval->team->id, $config, $config['highlight_fav']);
				?>
			</td>
	
			<?php
			if($type==3)
			{
			  $tabcols=3;
			}
			else
			{
			  $tabcols=1;
			}
			for ($tabs=0; $tabs < $tabcols; $tabs++)
			{
			  if ($tabs==0)
			  {
			    $showRow = $aval;
			  }
			  else
			  {
			    // search correct row
			    $otherrow = 0;
			    if ($tabs==1)
			    {
			      foreach ($homeRank AS $key => $value)
			      //while ($homeRank[$otherrow]->team->teamtoolid != $aval->team->teamtoolid)
			      {
			        //if ($key == $aval->team->teamtoolid) $otherrow++;
			        if (isset($homeRank[$key]->team->teamtoolid) && $homeRank[$key]->team->teamtoolid == $aval->team->teamtoolid) $showRow = $homeRank[$key];
			      }
			      //$showRow = $homeRank[$otherrow];
		
			    }
			    else
			    {
			      foreach ($awayRank AS $key => $value)
			      //while ($awayRank[$otherrow]->team->teamtoolid != $aval->team->teamtoolid)
			      {
			        //$otherrow++;
			        if (isset($awayRank[$key]->team->teamtoolid) && $awayRank[$key]->team->teamtoolid == $aval->team->teamtoolid) $showRow = $awayRank[$key];
			      }
			      //$showRow = $awayRank[$otherrow];
			    }
			  }
		  
			  // START OPTIONAL COLUMN DISPLAY
			  foreach ( $columns AS $c )
			  {
			  	switch ( trim( strtoupper( $c ) ) )
			  	{
			  		case 'PLAYED':
			        ?>
			        <td valign="top" <?php
			          if ( $color != '' && $type == 3 ) {
			            echo ' style="text-align:center;border-left: 1px solid; background-color: '.$color.'"';
			          }
			          else if ( $color != '' ) {
			            echo ' style="text-align:center;background-color: '.$color.'"';
			          }
			          else if ( $type == 3 ) {
			            echo ' style="text-align:center;border-left: 1px solid"'; 
			          }
			          else {
			            echo ' style="text-align:center;"';
			          }
			        ?> align="center">
			        <?php 
			        printf($format, $showRow->cnt_matches);
			        ?>&nbsp;
			        </td>
			        <?php
				  			break;
		
				  		case 'WINS':
		            ?>
			        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
			        printf($format, $showRow->cnt_won);?>&nbsp;</td>
			        <?php
			  				break;
			  				
		          case 'TIES':
		            ?>
			        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
			        printf($format, $showRow->cnt_draw);?>&nbsp;</td>
			        <?php
							break;
							
						case 'LOSSES':
			        ?>
			        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
			        printf($format, $showRow->cnt_lost);?>&nbsp;</td>
			        <?php
							break;
							
			      case 'WINPCT':
			        ?>
			        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
			        if (($showRow->cnt_won+$showRow->cnt_lost+$showRow->cnt_draw) > 0) {
			          printf($format, sprintf("%.3F",$showRow->cnt_won/($showRow->cnt_won+$showRow->cnt_lost+$showRow->cnt_draw)));
			        }
			        else printf($format, sprintf("%.3F",$showRow->cnt_won));
			        ?>&nbsp;</td>
			        <?php
			        break;
			        
			      case 'GB':
			        ?>
			        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center">
			        <?php printf($format,
			        round( (($ref_won - $showRow->cnt_won) - ($ref_lost - $showRow->cnt_lost))/2, 1)
			        );?> &nbsp;</td>
			        <?php
					      break;
					      
		          case 'LEGS':
				        ?>
			        <td valign="top" align="center" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>"><?php
			        printf($format, sprintf("%s:%s", $aval->sum_matchpart1_legs, $aval->sum_matchpart2_legs));?>&nbsp;</td>
			        <?php
		          	break;
		          	
							case 'LEGS_DIFF':
				        ?>
			        <td valign="top" align="center" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>"><?php
			        printf($format, $aval->diff_matchpart_legs);?>&nbsp;</td>
			        <?php
							break;
							
						case 'RESULTS':
							?>
			        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
			        printf($format, sprintf("%s:%s", $showRow->sum_matchpart1_result, $showRow->sum_matchpart2_result));?>&nbsp;</td>
			        <?php
							break;
							
						case 'DIFF':
			        ?>
			        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
			        printf($format, $showRow->diff_matchpart_results);?>&nbsp;</td>
			        <?php
							break;
							
						case 'POINTS':
							if( $config['show_negative_points'] == 1 )
							{
				        ?>
				        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
				        printf($format, sprintf("%s:%s", $showRow->sum_points, $showRow->neg_points));?>&nbsp;</td>
				        <?php
				      }
				      else {
				        ?>
				        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
				        printf($format, $showRow->sum_points);?>&nbsp;</td>
				        <?php
				      }
							break;
							
						case 'BONUS':
			        ?>
			        <td valign="top" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
			        printf($format, $showRow->bonus_points);?>&nbsp;</td>
			        <?php
							break;
							
			      case 'START':
			        ?>
			        <td valign="top" title="<?php echo $aval->team->info; ?>" style="text-align:center;<?php if($color!='') { echo 'background-color:'.$color; }?>" align="center"><?php
			        printf($format, $aval->team->start_points);?>&nbsp;</td>
			        <?php
				      break;
			  	}
			  }
				?>
				</tr>
				<?php
				$k = 1 - $k;
				$counter++;
				$temprank=$aval->rank;
			}
    }
  }

/**
 * generates column name as a link to sort data in column.
 * @param $columnTitle  string   the column name to be displayed
 * @param $paramName string the corresponding sorting parameter
 * @param $config array configuration parameters for ranking table
 * @param $default string default sorting order (ASC|DESC)
 * @return  string
 */
function print_column_heading_sort( $columnTitle, $paramName, $config, $default="DESC" ) {
  $output = "";
  $img='';
  //if (!array_key_exists('column_sorting',$config)) $config['column_sorting']=true;
  if ($config['column_sorting']) {
    $base_link=_JOOMLA_JL_LIVE_SITE."/".JL_COMPONENT_LINK
    ."&amp;func=".mosGetParam($_REQUEST, 'func', '')
    ."&amp;p=".mosGetParam($_REQUEST, 'p', '')
    ."&amp;Itemid=".mosGetParam($_REQUEST, 'Itemid', '')
    ."&amp;type=".mosGetParam($_REQUEST, 'type', '');

    if (mosGetParam($_REQUEST, 'order', '')==$paramName) {
      $link = $base_link."&amp;order=$paramName&amp;dir="
      .(mosGetParam($_REQUEST, 'dir', '')=='ASC'?'DESC':'ASC');
      $img = ' <img src="'._JOOMLA_JL_LIVE_SITE.'/components/com_joomleague/images/joomleague/sort'
      .(mosGetParam($_REQUEST, 'dir', '')=='ASC'?"02":"01").'.gif" alt="'.mosGetParam($_REQUEST, 'dir', '').'" />';
    }
    else {
      $link = $base_link."&amp;order=$paramName&amp;dir=$default";
    }
    echo '<a href="'.sefRelToAbs($link).'" class="jl_rankingheader">'.$columnTitle.'</a>'.$img;
  }
  else echo $columnTitle;
}

/**
 * print division name before ranking table
 * @param divLevel int level of subdivision: 0 for project, 1 for first sublevel...
 * @return id int array
 */
function show_ranking_division_title($divId) {
  global $database, $joomleague;
  if (!$divId) return;
  $div = New LeagueDivision ($database);
  $div->load($divId);
  //echo ($div->parent_id>0?_JL_TABLE_DIVISION_LEVEL2:_JL_TABLE_DIVISION_LEVEL1)." ".$div->name;
  echo $div->name;
}


	function show_ranking_heading($type, &$config) 
	{
	  global $joomleague;
		  
	  $colspanHead = 4;
	  if ($config['show_logo_small_table']>0){
	    $colspanHead++;
	  }
	  
    $columns = explode( ",", $config['ordered_columns'] );
	  $colspanSingleTab = count( $columns );
	
	  // Test for triple table
	  if( $type == 3 ) 
	  {
	    ?>
			<tr>
				<td align="left" width="50" colspan="<?PHP echo $colspanHead; ?>">&nbsp;</td>
				<td colspan="<?PHP echo $colspanSingleTab; ?>" align="center"
					style="text-align: center"><b><?PHP echo _JL_MODULE_RANKING_OVERALL; ?></b>
				</td>
				<td colspan="<?PHP echo $colspanSingleTab; ?>" align="center"
					style="text-align: center"><b><?PHP echo _JL_MODULE_RANKING_HOME; ?></b>
				</td>
				<td colspan="<?PHP echo $colspanSingleTab; ?>" align="center"
					style="text-align: center"><b><?PHP echo _JL_MODULE_RANKING_AWAY; ?></b>
				</td>
			</tr>
	    <?PHP 
	  } 
	  ?>
	<tr>
		<td align="left" class="sectiontableheader" width="50" colspan="3"><?php 
		$this->print_column_heading_sort( _JL_TABLE_POSITION , "rank", $config, "ASC");
		//echo _JL_TABLE_POSITION;
		?>
		</td>
		<?php
		if ( $config['show_logo_small_table'] )
		{
		  ?>
	    <td align="center" style="text-align: center"
			class="sectiontableheader" width="50">&nbsp;</td>
			<?php 
	  }
		?>
		<td align="left" class="sectiontableheader">
		<?php 
		$this->print_column_heading_sort( _JL_TABLE_TEAM , "name", $config, "ASC");
		//echo _JL_TABLE_TEAM;
		?>
		</td>
		<?php
		// three tables next to each other
		if ( $type == 3 )
		{
		  $tabcols = 3;
		}
		else
		{
		  $tabcols = 1;
		}
		
		for ( $tabs = 0; $tabs < $tabcols; $tabs++ )
		{
		  foreach ( $columns as $column )
		  {
		  	switch ( trim( strtoupper( $column ) ) )
		  	{
		  		case 'PLAYED':
		  			?>
					  <td align="center" class="sectiontableheader" style="text-align:center;<?php if($type==3) { echo 'border-left: 1px solid;';}?>"><?php
					  echo _JL_TABLE_MATCHES;?></td>
					  <?php
					  break;
					  
	        case 'WINS':
	          ?>
					  <td align="center" style="text-align: center"
					    class="sectiontableheader">
					  <?php $this->print_column_heading_sort( _JL_TABLE_WON , "won", $config); ?>
					  </td>
					  <?php
					  break;
					  
	        case 'TIES':
	          ?>
	          <td align="center" style="text-align: center"
	              class="sectiontableheader">
	          <?php $this->print_column_heading_sort( _JL_TABLE_DRAW , "draw", $config); ?>
	          </td>
	          <?php
	          break;
	          
					case 'LOSSES':  
					  ?>
					  <td align="center" style="text-align: center"
					    class="sectiontableheader"><?php $this->print_column_heading_sort( _JL_TABLE_LOSS , "loss", $config);
					    ?></td>
					  <?php
					  break;
					  
					case 'WINPCT':
					  ?>
					  <td align="center" style="text-align: center"
					    class="sectiontableheader"><?php $this->print_column_heading_sort( _JL_TABLE_WINPCT , "winpct", $config);
					  ?></td>
					  <?php
					  break;
					  
					case 'GB':
						  ?>
					  <td align="center" style="text-align: center"
					    class="sectiontableheader"><?php echo _JL_TABLE_GB;?></td>
					  <?php
					  break;
					  
					case 'LEGS':
						if ( $joomleague->use_legs == 1 )
						{
						  ?>
						  <td align="center" style="text-align: center"
						    class="sectiontableheader"><?php
						    if ($config['alternative_legs']=="") echo _JL_TABLE_LEGS;
						    else echo $config['alternative_legs'];
						    ?></td>
						    <?php
						}
						else {
							echo '<td>&nbsp;</td>';
						}
						break;
					case 'LEGS_DIFF':
						if( $joomleague->use_legs == 1 ) 
						{
						  ?>
						  <td align="center" style="text-align: center"
						    class="sectiontableheader"><?php
						    if ($config['alternative_legs_diff']=="") echo _JL_TABLE_LEGS_DIFF;
						    else echo $config['alternative_legs_diff'];
						    ?></td>
						    <?php
						}
            else {
              echo '<td>&nbsp;</td>';
            }
						break;
					case 'RESULTS':
						  ?>
					  <td align="center" style="text-align: center"
					    class="sectiontableheader"><?php
					    if ($config['alternative_goal']=="") $goals = _JL_TABLE_GOALS;
					    else $goals = $config['alternative_goal'];
					    $this->print_column_heading_sort( $goals , "goalsp", $config);
					    ?></td>
	          <?php
	          break;
					case 'DIFF':
						  ?>
					  <td align="center" style="text-align: center"
					    class="sectiontableheader"><?php $this->print_column_heading_sort( _JL_TABLE_DIFF , "diff", $config);
					    ?></td>
					  <?php
					  break;
				  case 'POINTS':
					  ?>
				    <td align="center" style="text-align: center"
				    class="sectiontableheader"><?php $this->print_column_heading_sort( _JL_TABLE_POINTS , "points", $config);
				    ?></td>
				    <?php
				    break;
					case 'BONUS':
					  ?>
					  <td align="center" style="text-align: center"
					    class="sectiontableheader"><?php $this->print_column_heading_sort( _JL_TABLE_BONUS_POINTS , "bonus", $config);
					    ?></td>
					  <?php
					  break;
					case 'START':
					  ?>
					  <td align="center" style="text-align: center"
					    class="sectiontableheader"><?php $this->print_column_heading_sort( _JL_TABLE_START_POINTS , "start", $config);
					    ?></td>
					    <?php
					  break;
		  	}
		  }
	  }
		?>
		</tr>
		<?php
		return $colspanHead + $colspanSingleTab;
	}
/****
 ####################################################################################################################
 Anzeige der Paarungen un Ergebnisse im Frontend
 ####################################################################################################################
 ****/
function show_report_icon ($match_id) {
  global $joomleague;
  $mrl='<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showReport&amp;p='.$joomleague->id.'&amp;mid='
  .$match_id.JL_ITEMID_SUFFIX).'"><img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/details.gif" border="0" alt="'
  ._JL_RESULTS_DETAIL_ICON.'" title="'._JL_RESULTS_DETAIL_ICON.'" /></a>';
  return $mrl;
}

	  
	/**
	 * print division remark
	 * 
	 * @param Object reference $hometeam
	 * @param Object reference $guestteam
	 * @param Array $config
	 */
	function showDivisonRemark(&$hometeam, &$guestteam, &$config) {
	  global $joomleague;
	  
	  if (!isset($config['spacer'])) $config['spacer'] = '/';
	  $nametype="division_".$config['show_division_name'];
	  $output='';
	    
	  if ($config['show_division_link'] == 1) {
	  $output .= '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showResultsRank&amp;p='.$joomleague->id.'&amp;division='
	    .($hometeam->division_id).JL_ITEMID_SUFFIX).'">';
	  }
	  $output .= $hometeam->$nametype;
	  
	  if ($config['show_division_link'] == 1) {
	    $output .= '</a>';
	  }
	  
	  if ($hometeam->division_id != $guestteam->division_id) {
	    $output .= $config['spacer'];
	    
	    if ($config['show_division_link'] == 1) {
	      $output .= '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showRanking&amp;p='.$joomleague->id.'&amp;division='
	      .($guestteam->division_id).JL_ITEMID_SUFFIX).'">';
	    }
	    
	    $output .= $guestteam->$nametype;
	    if ($config['show_division_link'] == 1) {
	      $output .= '</a>';
	    }
	  }
	  return $output;
	}
	 
	/**
	 * display a row in match results table
	 *
	 * @param object $matchInfo
	 * @param object $teamsInfo
	 * @param array $favteam
	 * @param array $config
	 */
	function show_match_row (&$matchInfo, &$teamsInfo, &$favteam, &$config) {
	  global $joomleague, $database;
	  
	  $divLevel = intval(mosGetParam($_REQUEST, 'division', 0));
	  $hometeam = $teamsInfo[$matchInfo->matchpart1];
	  $guestteam = $teamsInfo[$matchInfo->matchpart2];
	  
	  ?>
	  <tr class="<?php echo $config['class'];?>">
	  <?php
	  if ($config['show_match_number']==1) {
	    ?>
	    <td align="left" nowrap="nowrap" valign="top"><?php
	    echo $matchInfo->match_number;?>&nbsp;</td>
	    <?php
	  }
	  if ($config['show_events']==1) {
	    ?>
	    <td align="left" nowrap="nowrap" valign="top"><?php
	    $are_there_events = $joomleague->areThereEvents ($matchInfo->match_id);
	    if ($are_there_events > 0 || $matchInfo->match_result_detail!="") {
	      ?> <a href="javascript:void(0);"
	      onclick="switchMenu('info<?php echo $matchInfo->match_id;?>');return false;"
	      title="<?php
	             echo _JL_SHOW_INFO;?>"> <img
	      src="<?php echo _JOOMLA_JL_LIVE_SITE;?>/administrator/components/com_joomleague/images/events.png"
	      alt="<?php
	             echo _JL_SHOW_INFO;?>"
	      title="<?php echo _JL_SHOW_INFO;?>" border="0" /></a> <?php
	    }
	    ?></td>
	    <?php
	  }
	  if ($joomleague->project_type=='DIVISIONS_LEAGUE' && isset($config['show_division']) && $config['show_division']==1) {
	    ?>
	    <td nowrap="nowrap" valign="top" style="text-align: center"><?php
	    if (isset($config['results_below']) && $config['results_below']==1) {
	      $config['spacer'] = '<br />';
	    }
	    echo $this->showDivisonRemark($hometeam, $guestteam, $config);
	    ?></td>
	    <?php
	  }
	  if ($config['show_playground']==1) {
	    ?>
	    <td nowrap="nowrap" valign="top" style="text-align: center"><?php
	    $this->showPlayground($hometeam, $guestteam, $matchInfo, $config['show_playground_alert'], $config['show_playground_name'] );
	    ?></td>
	    <?php
	  }
	  if ($config['show_time']==1) {
	    ?>
	    <td nowrap="nowrap" valign="top"><?php
	    echo $this->format_match_time($matchInfo, $joomleague, $config);
	    ?></td>
	    <?php
	  }
	  if (isset($config['results_below']) && $config['results_below']==1){
		  if ($config['show_logo_small'] > 0) {
		    ?>
		    <td align="center" valign="top" nowrap="nowrap" style="width: 5%;"><?php
		    $this->showClubIcon($hometeam, $config['show_logo_small'], 1);
		    echo '<br />';
		    $this->showClubIcon($guestteam, $config['show_logo_small'], 1);
		    ?></td>
		    <?php
		  }
	    ?>
	
		  <td align="left" valign="top" width="30%" nowrap="nowrap"><?php
			  $namehighlight=(in_array($hometeam->id, $favteam)) ? 1 : 0;
			  $namebold = (isset($team_plan)&&$team_plan->id == $hometeam->id) ? 1 : 0;
			  echo $this->formatTeamname ($hometeam, 'm'.$matchInfo->match_id, $config, $namehighlight, $namebold, $matchInfo->project_id);
			  echo '<br />';
			  $namehighlight=(in_array($guestteam->id, $favteam)) ? 1 : 0;
			  $namebold = (isset($team_plan)&&$team_plan->id == $guestteam->id) ? 1 : 0;
			  echo $this->formatTeamname ($guestteam, 'm'.$matchInfo->match_id, $config, $namehighlight, $namebold, $matchInfo->project_id);
			  ?>
		  </td>
	  	  <?php
	  	  echo $this->show_result_below($matchInfo, $config['show_part_results']);
	  }
	  else {
	  	// TeamA
	  	$namehighlight=(in_array($hometeam->id, $favteam)) ? 1 : 0;
      $namebold = (isset($team_plan)&&$team_plan->id == $hometeam->id) ? 1 : 0;
      
	  	$teamA_html = "";
		  if ($config['show_logo_small'] > 0) {
		    $teamA_html = '<td align="right" valign="top" nowrap="nowrap" style="width: 5%;">'
		                  .$this->getClubIconHtml($hometeam, $config['show_logo_small'])
									    .'</td>';
		  }
		  $teamA_html .= '<td align="left" valign="top" width="30%" nowrap="nowrap">';
		  $teamA_html .= $this->formatTeamname ($hometeam, 'm'.$matchInfo->match_id, $config, $namehighlight, $namebold, $matchInfo->project_id);
			$teamA_html .= '</td>';
		  
		  $separator = '<td align="left" valign="top" width="5%" nowrap="nowrap">-</td>';

		  //Team B
      $namehighlight=(in_array($guestteam->id, $favteam)) ? 1 : 0;
      $namebold = (isset($team_plan)&&$team_plan->id == $guestteam->id) ? 1 : 0;
      
      $teamB_html = "";
      if ($config['show_logo_small'] > 0) {
        $teamB_html = '<td align="right" valign="top" nowrap="nowrap" style="width: 5%;">'
                      .$this->getClubIconHtml($guestteam, $config['show_logo_small'])
                      .'</td>';
      }
      $teamB_html .= '<td align="left" valign="top" width="30%" nowrap="nowrap">';
      $teamB_html .= $this->formatTeamname ($guestteam, 'm'.$matchInfo->match_id, $config, $namehighlight, $namebold, $matchInfo->project_id);
      $teamB_html .= '</td>';
      
      $score_html = '<td align="right" valign="top" nowrap="nowrap">'
                    .$this->show_result($matchInfo, $config['show_part_results'])
                    .'</td>';
                    
      switch ($config['result_style']) {
      	case 0 :
          echo $teamA_html.$separator.$teamB_html.$score_html;
          break;
        case 1 :
          echo $teamA_html.$score_html.$teamB_html.'<td>&nbsp;</td>';
          break;
      }
		}
	  ?>
	  <td align="center" valign="top" nowrap="nowrap"><?php
		  if($matchInfo->show_report == 1) {
		    echo $this->show_report_icon($matchInfo->match_id);
		  }
		  ?>
	  </td>
	  <?php
	  if ( $config['show_referee']) {
	    ?>
	    <td align="right" valign="top" nowrap="nowrap"><?php
		    if (!is_null($matchInfo->referee_id) and $matchInfo->referee_id>0) {
		      //echo $this->show_referee($matchInfo->referee_id, $joomleague->teams_as_referees);
		      if ($joomleague->teams_as_referees) echo $matchInfo->referee_name;
		      else echo $matchInfo->referee_lastname.", ".$matchInfo->referee_firstname;
		    } ?>
	    </td>
	    <?php
	  }
	  $matchInfo->home = $hometeam->name;
	  $matchInfo->away = $guestteam->name;
	  if ($joomleague->enable_sb && $config['show_fireboard_link']) {
		  ?>
			  <td align="right" valign="top" nowrap="nowrap"><?php echo $this->make_forumlink($matchInfo);?>
			  </td>
		  </tr>
		  <?php
    }
	  if ($config['show_events']==1 && ($are_there_events > 0 || $matchInfo->match_result_detail!="")) {
	    $this->show_events_container_in_results($matchInfo, 'none', $config);
	  }
	}
	
	function show_result(&$match, $show_part_results=0) {
	  global $joomleague;
	  $matchresulttype=array('', _JL_RESULTS_OVERTIME, _JL_RESULTS_PENALTY);
	  $goalshome = (is_null($match->matchpart1_result)) ? "-" : $match->matchpart1_result;
	 	$goalsaway = (is_null($match->matchpart2_result)) ? "-" : $match->matchpart2_result;
	 	$mrt = $matchresulttype[$match->match_result_type];
	  if ($match->alt_decision == 1) {
	    $mrt = '<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/court.gif" border="0" alt="'.$match->decision_info.'" title="'.$match->decision_info
	    .'" border="0" />';
	    $goalshome = (isset($match->matchpart1_result_decision)) ? $match->matchpart1_result_decision : 'X';
	    $goalsaway = (isset($match->matchpart2_result_decision)) ? $match->matchpart2_result_decision : 'X';
	  }
	  $result = $goalshome.'</td><td valign="top" width="1px">:</td><td align="left" valign="top" nowrap>'.$goalsaway;
	  
	  if ($joomleague->use_legs==1) $result .= " (".$match->matchpart1_legs.":".$match->matchpart2_legs.")";
	  
	  if ($show_part_results == 1 && !is_null($match->matchpart1_result_split) && str_replace(';', '', $match->matchpart1_result_split) != '') {
	    $homepartresults=explode(";", $match->matchpart1_result_split);
	    $guestpartresults=explode(";", $match->matchpart2_result_split);
	    $result .= " (";
	    for ($x=0;$x < ($joomleague->game_parts);$x++) {
	      if (isset($homepartresults[$x]) && isset($guestpartresults[$x]) &&
	      $homepartresults[$x]!='' && $guestpartresults[$x]!='') {
	        if ($x!=0) $result .= "-";
	        $result .= $homepartresults[$x].":".$guestpartresults[$x];
	      }
	    }
	    if ( $match->match_result_type && $match->matchpart1_result_ot != null ) {
	     $result .= '-' . $match->matchpart1_result_ot . ':' . $match->matchpart2_result_ot;
	    }
	    $result .= ")";
	  }
	  $result .= '<td width="1px" nowrap="nowrap">'.$mrt.'</td>';
	  return $result;
	}
	
	function show_result_below(&$match, $show_part_results=0) {
	  global $joomleague;
	  $matchresulttype=array('', _JL_RESULTS_OVERTIME, _JL_RESULTS_PENALTY);
	  $goalshome = (is_null($match->matchpart1_result)) ? "--" : $match->matchpart1_result;
	 	$goalsaway = (is_null($match->matchpart2_result)) ? "--" : $match->matchpart2_result;
	 	$mrt = $matchresulttype[$match->match_result_type];
	  
	 	if ($match->alt_decision == 1) {
	    $mrt = '<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/court.gif" border="0" alt="'.$match->decision_info.'" title="'.$match->decision_info
	    .'" border="0" />';
	    $goalshome = (isset($match->matchpart1_result_decision)) ? $match->matchpart1_result_decision : 'X';
	    $goalsaway = (isset($match->matchpart2_result_decision)) ? $match->matchpart2_result_decision : 'X';
	  }
	  
	  $result = '';
	  if ($show_part_results == 1) {
	    $homepartresults=explode(";", $match->matchpart1_result_split);
	    $guestpartresults=explode(";", $match->matchpart2_result_split);
	    //$result .= " (";
	    $partScoreSum_home = 0;
	    $partScoreSum_guest = 0;
	    for ($x=0;$x < ($joomleague->game_parts);$x++) {
	      if (isset($homepartresults[$x]) && isset($guestpartresults[$x]) &&
	      $homepartresults[$x]!='' && $guestpartresults[$x]!='') {
	       // if ($x!=0) $result .= "-";
	        $partScoreSum_home += (float) $homepartresults[$x];
	        $partScoreSum_guest += (float) $guestpartresults[$x];
	        $result .= '<td style="text-align:right">'.$homepartresults[$x].'<br />'.$guestpartresults[$x].'</td>';
	      }
	      else $result .= '<td style="text-align:right">--<br />--</td>';
	    }
	  }
	  
	  if ($joomleague->allow_add_time == 1 && $mrt!='') {
	    //$OTScore_home = $goalshome - $partScoreSum_home;
	    //$OTScore_guest = $goalsaway - $partScoreSum_guest;
	    $OTScore_home = $match->matchpart1_result_ot;
	    $OTScore_guest = $match->matchpart2_result_ot;
	    $result .= '<td style="text-align:right">'.$OTScore_home.'<br />'.$OTScore_guest.'</td>';
	  }
	  elseif ($joomleague->allow_add_time == 1) $result .= '<td style="text-align:right">&nbsp;</td>';
	  //$result .= '<td>'.$mrt.'</td>';
	  $result .= (is_null($match->matchpart1_result)&&$partScoreSum_home>0) ? '<td style="text-align:right;color:#ff0000;"><b>'
	    .$partScoreSum_home.'<br />'.$partScoreSum_guest.'</b></td>' : 
	    '<td style="text-align:right"><b>'.$goalshome.'<br />'.$goalsaway.'</b></td>';
	  if ($joomleague->allow_add_time == 1) $result.= '<td style="text-align:right">&nbsp;</td>';	  
    if ($joomleague->use_legs==1) $result .= '<td style="text-align:right">'.$match->matchpart1_legs.'<br />'.$match->matchpart2_legs.'</td>';
	  $result .= '<td>'.$mrt.'</td>';
    return $result;
	}

	/**
	 * Compute colspans and store $config
	 *
	 * @param array $config
	 * @param bool  $for_edit
	 */
	function resultsColspan (&$config, $for_edit=false) {
	  global $joomleague;
	  // if we are in edit mode we don't need no cols except matchnumber if chosen in config
	  if ($for_edit) {
	    $colspan_with_names = (isset($config['results_below'])&&$config['results_below']==1) ? 3 : 5;
	    if ($config['show_match_number'] == 1) $colspan_with_names++;
	  }
	  // else for results display
	  else {
	    //teamnames are always visible, 3 columns for regular, 1 for two rows in e.g. basketball
	    $colspan_with_names = (isset($config['results_below'])&&$config['results_below']==1) ? 1 : 5;
	    // first for these before team names
	    if ($config['show_match_number'] == 1) $colspan_with_names++;
	 
	    if ($joomleague->project_type=='DIVISIONS_LEAGUE' && $config['show_division']==1) $colspan_with_names++;
	    if ($config['show_events'] == 1) $colspan_with_names++;
	    if ($config['show_playground'] > 0) $colspan_with_names++;
	    if ($config['show_time'] >0)  $colspan_with_names++;
	    if ($config['show_logo_small'] > 0) {
	      if (isset($config['results_below'])&&$config['results_below']==1) $colspan_with_names += 1;
	      else $colspan_with_names += 2;
	    }
	  }
	  //now these after team names
	  //report icon is always one column
	  // result is always a column
	  $colspan_after_names = 2;
	  if (isset($config['results_below'])&&$config['results_below']==1) $colspan_after_names += $joomleague->game_parts;
	  if ($config['show_referee'] == 1) $colspan_after_names++;
	  if ($joomleague->allow_add_time > 0)  $colspan_after_names++;
	  if ($joomleague->enable_sb && $config['show_fireboard_link']) $colspan_after_names++;
	  // now we set the results to use in display
	  $config['first_colspan'] = $colspan_with_names;
	  $config['second_colspan'] = $colspan_after_names;
	  $config['colspan'] = ($colspan_with_names + $colspan_after_names);
	}

	/**
	 * returns name of referee
	 *
	 * @param int $referee_id
	 * @param boolean $use_teams
	 * @return string
	 */
  function show_referee($referee_id, $use_teams=false) {
    global $database;
    $refname = '-';
    if ($use_teams) {
      $query = "SELECT name FROM #__joomleague_teams WHERE id = $referee_id";
      $database->setQuery($query);
      if ( !$refname = $database->loadResult() )
        $refname = "-";
    }
    else {    
      $query = "SELECT firstname, lastname FROM #__joomleague_referees WHERE id = $referee_id";
      $database->setQuery($query);
      if ( !$ref = $database->loadObject() ) $refname = "-";
      else $refname = $ref->lastname.", ".$ref->firstname;
    }
    return $refname;
  }

  /**
   * echo playground information
   *
   * @param Object hometeam
   * @param Object guestteam
   * @param Object match
   * @param boolean show alert 
   * @param string type of name ()
   */
  function showPlayground(&$hometeam, &$guestteam, &$match, $alert=0, $type='name'){
    global $database, $joomleague;
    $thispgid=0;
    
    if ( is_null( $match->playground_id ) || $match->playground_id == 0 ) {
      $thispgid=$hometeam->standard_playground;
	    
      if ( $type == 'shortname' ) {
        $string_playground = $hometeam->playground_short_name;      
      }
      else {
        $string_playground = $hometeam->playground_name;
      }      
    }
    else
    {
      $thispgid=$match->playground_id;
      if ( $type == 'shortname' ) {
        $string_playground = $match->playground_short_name;      
      }
      else {
        $string_playground = $match->playground_name;
      } 
    }
    
    // display if playground exists
    if ( $thispgid != 0 && $thispgid != '' && !is_null($thispgid) ) {
      $playground_link=sefRelToAbs( JL_COMPONENT_LINK."&amp;func=showPlayground&amp;pgid=$thispgid&amp;p=$joomleague->id"
      .JL_ITEMID_SUFFIX);
      
      // show an alert if game playground is not the default playground for home team ?
      if ( !is_null($match->playground_id) 
        && $match->playground_id != $hometeam->standard_playground 
        && $alert==1 ) 
      {
        mosCommonHTML::loadOverlib();
        //load whole infos for playground
	      $pginfo = new Playground ($database);
	      $pginfo->load($thispgid);
        
        $caption = sprintf(_JL_MATCH_EVACUATED, $hometeam->name, $guestteam->name);
        $newplayground = _JL_NEW_PLAYGROUND.":<br /><b>".$pginfo->name."</b><br />".$pginfo->address."<br />".$pginfo->zip." ".$pginfo->city;
        $match->match_result_detail .= $caption."<br />".$newplayground;
        echo '<a href="'.$playground_link.'" onmouseover="return overlib(\''.$newplayground.'\', CAPTION, \''.$caption
        .'\', BELOW, RIGHT);" onmouseout="return nd();">
        <img src="'._JOOMLA_JL_LIVE_SITE
        .'/administrator/components/com_joomleague/images/information.png" width="16" height="16" border="0" alt="INFO" title="INFO" align="top" />
        <acronym title="'.$pginfo->name.'">'.$string_playground.'</acronym></a>';
      }
      else {
        echo '<a href="'.$playground_link.'"><acronym title="'.$match->playground_name.'">'.$string_playground.'</acronym></a>&nbsp;';
      }
    }
    else // playground not defined
    {
      echo '-';
    }
  }
  	
	function showClubIcon(&$team, $type=1, $with_space=0) {
	  global $joomleague;
	  
	  $small_club_icon = $team->logo_small;
	  
	  if ($type==1 && isset($team->country)) {
	    $tempname=explode("/", $team->logo_small);
	    $picname = $tempname[count($tempname)-1];
	    if ( file_exists(_JOOMLA_JL_PATH.'/'.$team->logo_small)
	        && $team->logo_small!="") {
	        ?>
				  <img src="<?php echo _JOOMLA_JL_LIVE_SITE."/".$team->logo_small; ?>"
					     alt="<?php echo $team->short_name ?>"
					     title="<?php	echo $team->name ?>" 
					     align="top" border="0" 
					     <?php 
					      if ($with_space==1) echo ' style="padding:1px;"';
					     ?>
					 />
					 <?php 
	    }
			else echo "&nbsp;";
		}
		else if ($type == 2 && isset($team->country)) {
		  $country = new Country($joomleague->_db);
		  $country->load($team->country);
		  echo $country->getFlag();
		}
	}

  /**
   * return club image in html img code
   *
   * @param object $team
   * @param int $type
   * @param boolean $with_space
   * @return html code
   */
  function getClubIconHtml(&$team, $type=1, $with_space=0) {
    global $joomleague;
    
    $small_club_icon = $team->logo_small;
  
    if ($type==1 && isset($team->country)) {
      $tempname=explode("/", $team->logo_small);
      $picname = $tempname[count($tempname)-1];
      if ( file_exists(_JOOMLA_JL_PATH.'/'.$team->logo_small)
          && $team->logo_small!="") {
        $html = '<img src="'._JOOMLA_JL_LIVE_SITE."/".$team->logo_small.'"'
                   .' alt="'.$team->short_name.'"'
                   .' title="'.$team->name.'"'
                   .' align="top" border="0"';               
        if ($with_space==1) $html .=' style="padding:1px;"';
        $html .='/>';
        return $html;
      }
      else return "&nbsp;";
    }
    else if ($type == 2 && isset($team->country)) {
      $country = new Country($joomleague->_db);
      $country->load($team->country);
      return $country->getFlag();
    }
  }

	
	function formatTeamname ($team, $containerprefix, &$config, $fav=0, $plan=0, $projectId = 0) {
	  // highlight: 1st param is for fav_team and 2nd for selected team in match plan
	  global $joomleague;
	  $projectId = ( $projectId > 0 ? $projectId : $team->project_id );
	  $teamtool_id = $team->teamtoolid;
	  $output='';
	  $js_func = 'switchMenu';
	  $style_append = 'display:none';
	  $container = 'div';
	  if (isset($config['results_below']) && $config['results_below'] == 1 && $config['show_logo_small'] == 1) {
	    $js_func = 'visibleMenu';
	    $style_append = 'visibility:hidden';
	    $container = 'span';
	  }
	  if ( ($config['show_icons']==2 && $fav == 1) || $config['show_icons']==1 &&
	  ($config['show_club_link']==1||$config['show_team_link']==1||$config['show_curve_link']==1
	  ||$config['show_plan_link']==1||$config['show_teaminfo_link']==1) ) {
	    $output .= '<a href="javascript:void(0);" onclick="'.$js_func.'(\''.$containerprefix.'t'.$team->id.'p'.$team->project_id.
	       '\');return false;" title="'._JL_SHOW_OPTIONS.'">';
	  }
	  if($config['highlight_fav']==1&&$fav==1){ $output .= '<span style="padding:2px;background-color:'.$joomleague->fav_team_color.'">';}
	  if ($plan==1) $output .=  "<b>";
	  if ($config['names']=='short_name') $output .=  '<acronym title="'.$team->name.'">'.$team->short_name.'</acronym>';
	  else $output .= (isset($team->$config['names'])) ? $team->$config['names'] : $team->name;
	  if ($plan==1) $output .=  "</b>";
	  if($config['highlight_fav']==1&&$fav==1){ $output .=  '</span>';}
	
	  if ( ($config['show_icons']==2 && $fav == 1) || $config['show_icons']==1 &&
	  ($config['show_club_link']==1||$config['show_team_link']==1||$config['show_curve_link']==1
	  ||$config['show_plan_link']==1||$config['show_teaminfo_link']==1) ) {
	    $output .= '</a><'.$container.' id="'.$containerprefix.'t'.$team->id.'p'.$team->project_id.'" style="'.$style_append.';">';
	    $output .= $this->show_team_icons ($team, $config, $projectId);
	    $output .= '</'.$container.'>';
	  }
	  return $output;
	}

/*******
 ###########################################################################################################
 ENDE
 ###########################################################################################################
 *******/
	
	function make_forumlink(&$match){
	  global $joomleague, $database;
	  static $sbItemid = 0; //doesn't change much from one call to he other...
	  
	  if ( $sbItemid == 0 ) { //this way, we only trig this request once
		  $database->setQuery("SELECT id FROM #__menu WHERE link='index.php?option=com_fireboard'");
		  $sbItemid = $database->loadResult();
	  }
	  if($joomleague->enable_sb == 0) return '';
	  $title = sprintf("%s - %s",addslashes($match->home),addslashes($match->away));
	
	  $query = sprintf("SELECT id FROM #__fb_messages WHERE catid =%s AND subject = '%s'",$joomleague->sb_catid, $title);
	  $database->setQuery($query);
	  $resultid = $database->loadResult();
	
	  $title = sprintf("%s - %s",$match->home,$match->away);
	  if ($resultid == ""){
	    $showlink = ("index.php?option=com_fireboard&amp;Itemid=$sbItemid"
	    . "&amp;mid=" . $match->match_id
	    . "&amp;p=" . $joomleague->id
	    . "&amp;func=post&amp;do=newFromJoomLeague&amp;resubject=".strtr(base64_encode($title), "+/", "()")."&amp;catid=".$joomleague->sb_catid
	    ."");
	    $countPosts = 0;
	    return sprintf('<a href="%s"><img src="'.JL_TEMPLATE_FOLDERS_URL
	    .'/images/discuss.gif" border="0" alt="%s" title="%s" /></a>',$showlink,_JL_RESULTS_JOOMLABOARD_LINK,_JL_RESULTS_JOOMLABOARD_LINK);
	  }
	  else{
	     
	    $joomleague->_db->setQuery("SELECT count(id) from #__fb_messages where thread = $resultid");
	    $countPosts = $joomleague->_db->loadResult();
	
	    $showlink = sefRelToAbs("index.php?option=com_fireboard&amp;Itemid=" .$sbItemid. "&amp;func=view&amp;id=" .$resultid. "&amp;catid=" .$joomleague->sb_catid. "");
	    return sprintf('<a href="%s"><img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/discuss_active.gif" border="0" alt="%s %s" title="%s %s" /></a>',$showlink,$countPosts,_JL_RESULTS_JOOMLABOARD_COUNT,$countPosts,_JL_RESULTS_JOOMLABOARD_COUNT);
	  }
	}

	/**
	 * Print edit/save icon according to task
	 *
	 * @param int $round
	 * @param string $task
	 */
	function show_edit_icon ($round, $task) {
	  global $joomleague;
	   
	  if( defined('JL_SHOW_EDIT_ICON')){
	    if ($task=="editresults") {
	      echo '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showResults&amp;p='.$joomleague->id.'&amp;r='.$round.JL_ITEMID_SUFFIX)
	      .'" title="'._CMN_CANCEL.'">
	    <img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/edit_exit.png" border="0" alt="'._CMN_CANCEL.'" title="'._CMN_CANCEL.'" /></a>';
	    }
	    else {
	      echo '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=editResults&amp;p='.$joomleague->id.'&amp;r='.$round.JL_ITEMID_SUFFIX)
	      .'" title="'._JL_RESULTS_EDIT.'">
	    <img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/edit.png" border="0" alt="'._JL_RESULTS_EDIT.'" title="'._JL_RESULTS_EDIT.'" /></a>';
	    }
	  }
	}

	
	function show_edit_icon_tipp () {
	  global $joomleague;
	  global $mytask;
	
	  $replace1 = array("&mytask=edit", "&");
	  $replace2 = array("", "&amp;");
	  if ($mytask=="edit")
	  echo '<a href="'.str_replace($replace1, $replace2, trim($_SERVER['REQUEST_URI'])).'" title="'._CMN_CANCEL.'">
	    <img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/edit_exit.png" border="0" alt="'._CMN_CANCEL.'" title="'._CMN_CANCEL.'" /></a>';
	  else echo '<a href="'.str_replace($replace1, $replace2, trim($_SERVER['REQUEST_URI'])).'&amp;mytask=edit" title="'._JL_RESULTS_EDIT.'">
	    <img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/edit.png" border="0" alt="'._JL_RESULTS_EDIT.'" title="'._JL_RESULTS_EDIT.'" /></a>';
	
	}

	/**
	 * returns html list of susbstitutions
	 *
	 * @param array $substitutions going in
	 * @param array $config
	 * @return string html
	 */
	function format_substitutes(&$substitutions, &$config) {
	  
	  $in_out = '<table class="jlg_substitutions">';
	  for ($x=0;$x < count($substitutions); $x++) {
	    $in_out .= '<tr><th width="5px" valign="top">';
	    // display substitution time
	    if ((isset($substitutions[$x-1]->in_out_time) && $substitutions[$x-1]->in_out_time != $substitutions[$x]->in_out_time) || $x == 0) {
	      $time = (!is_null($substitutions[$x]->in_out_time) && $substitutions[$x]->in_out_time > 0) ? $substitutions[$x]->in_out_time."'" : '';
	      $in_out .=  $time;
	    }
	    $in_out .= '</th><td>';
	    // player going out
	    if ($substitutions[$x]->in_for) {
	       $in_out .= ' <img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/out.png" alt="ausgewechselt" /> ';
	       $in_out .=  "<a href=\"".sefRelToAbs(JL_COMPONENT_LINK."&amp;func=showPlayer&amp;p=".$substitutions[$x]->project_id."&amp;pid="
	                 .$substitutions[$x]->in_for.JL_ITEMID_SUFFIX).'">';
	       $in_out .=  $substitutions[$x]->out_lastname;
	       if ($substitutions[$x]->out_firstname != '') $in_out .= ', '.$substitutions[$x]->out_firstname;
	       $in_out .= '</a>';
	       $in_out .= ' ('.$substitutions[$x]->out_position.') <br />';
	    }
	    // player going in
	    $in_out .= '<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/in.png" alt="eingewechselt" /> ';
	    $in_out .=  "<a href=\"".sefRelToAbs(JL_COMPONENT_LINK."&amp;func=showPlayer&amp;p=".$substitutions[$x]->project_id."&amp;pid="
	                 .$substitutions[$x]->player_id.JL_ITEMID_SUFFIX).'">';
	    $in_out .= $substitutions[$x]->lastname;
	    if ($substitutions[$x]->firstname != '') $in_out .= ', '.$substitutions[$x]->firstname;
	    $in_out .= '</a>';
	    $in_out .= ' ('.$substitutions[$x]->in_position.') ';
	    
	    $in_out .= '</td></tr>';
	  }
	  $in_out .= '</table>';
	
	  return $in_out;
	}

	function show_events_container_in_results (&$matchInfo, $display, &$config, $withinout = 1) 
	{
	  global $joomleague, $database;
	  $match = new Match($database);
	  $match->bind(get_object_vars($matchInfo));
	  
	  if ( $display == 'none' ) 
	  {
      ?>
	    <tr class="<?php echo $config['class'];?>">
        <td colspan="<?php echo $config['colspan'];?>">
      <?php 
	  }
	  ?>
	  <div id="info<?php echo $match->match_id;?>" style="display:<?php echo $display;?>;width:100%">
    <?php
    
		if ( $config['use_tabs_events']==1 )
		{
		  // Init tab class
      $joomleague_tabs = new JLTabs(1);
		  // create pane for this game
      $style = '';
      $joomleague_tabs->startPane( 'game'.$match->match_id );
		  
      // add a tab for match details
      if ( $match->match_result_detail != "" ) 
		  {
		    $infoheading = '<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/event_icons/note.png" alt="'._JL_NOTICE.'" title="'
		    ._JL_NOTICE.'" align="top" hspace="2" border="0"  /> '._JL_NOTICE;
		    // $joomleague_tabs->makeTab( 'matchinfo'.$match->match_id, $infoheading, $match->match_result_detail);
		    $joomleague_tabs->startTab( $infoheading, 'matchinfo'.$match->match_id );
		    echo $match->match_result_detail;
		    $joomleague_tabs->endTab();
		  }
		}
		else 
		{
		  $style=' style="border:1px dotted;"';
		  if ($match->match_result_detail!="") {
			  echo _JL_NOTICE.': '.$match->match_result_detail.'<br/>';
		  }
		}
		
		// infos for each event
		$temp = $joomleague->getEventTypes();
		if ( count( $temp ) )
		{
			foreach ( $temp AS $et ) 
			{
			  $homeevents = $joomleague->getMatchEventsID($match->match_id, $match->matchpart1, $et->id);
			  $awayevents = $joomleague->getMatchEventsID($match->match_id, $match->matchpart2, $et->id);
			  
			  if ( count($homeevents) > 0 || count($awayevents) > 0 ) 
			  {
			    // heading for event
			  	$eventsheading = '<img src="'._JOOMLA_JL_LIVE_SITE.'/images/joomleague/event_icons/'.$et->icon.'" 
			                           alt="'.$et->name.'" 
			                           title="'.$et->name.'" 
			                           align="top" hspace="2" border="0" />'.$et->name;
			    //content
			    $eventscontent = '<table width="100%"'.$style.' 
			                             cellspacing="0" 
			                             cellpadding="2">';
			    
			    $eventscontent .= '<tr>';
			    
			    // events for home team
			    $eventscontent .= '<td width="50%" valign="top"'.$style.'>
                                <ul class="reporteventlist">';
			    if ( count( $homeevents ) )
			    {
			      $counter = 1;
			      foreach ( $homeevents AS $event )
			      {
			      	$thisevent = new MatchEvent( $database );
			      	//TODO: there should be a gloal request instead of one request per event/match/player 
			        $thisevent->load( $event->event_id );
			        $eventscontent .= $this->getEventListItem( $thisevent );
			      }
			      unset($homeevents);
			    }
			    
			    // event for away team
			    $eventscontent .= '</ul></td><td valign="top"'.$style.'><ul class="reporteventlist">';
			    if (count($awayevents) > 0) 
			    {
			      $counter = 1;
			      foreach ( $awayevents AS $event ) 
			      {
			        $thisevent = new MatchEvent( $database );
			        $thisevent->load( $event->event_id );
			        $eventscontent .= $this->getEventListItem( $thisevent );
			      }
			      unset($awayevents);
			    }
			    $eventscontent .= '</ul></td></tr></table>';
		
			    // display event
			    if ( $config['use_tabs_events']==1 ) 
			    {
            //$joomleague_tabs->makeTab( 'event'.$match->match_id.$et->id, $eventsheading, $eventscontent);
			      $joomleague_tabs->startTab( $eventsheading, 'event'.$match->match_id.$et->id );
	          echo $eventscontent;
	          $joomleague_tabs->endTab();
			    }
			    else {
			    	//TODO: maybe divs with float 'left' ?
            echo $eventsheading.'<br />'.$eventscontent;
			    }
			  }
			}
		}
		
		// in / out informations
		if ( $withinout == 1 ) 
    {
		  $came_in = $match->getSubstitutes();
		  if ( count($came_in[$match->matchpart1]) > 0 || count($came_in[$match->matchpart2]) > 0 ) 
		  {
		    // headed
		  	$inout_head = '<img src="'._JOOMLA_JL_PATH.'/images/joomleague/event_icons/subst.png" alt="'._JL_NOTICE.'" title="'
			    ._JL_NOTICE.'" align="top" hspace="2" border="0"  /> Ein- / Ausw.';
			  
			  // table with home and away
			  $in_out = '<table width="100%"'.$style.' cellspacing="0" cellpadding="2"><tr><td width="50%" valign="top"'.$style.'>';
		    $in_out .= $this->format_substitutes($came_in[$match->matchpart1], $config);
		    $in_out .= '</td><td width="50%" valign="top"'.$style.'>';
		    $in_out .= $this->format_substitutes($came_in[$match->matchpart2], $config);
		    $in_out .= '</td></tr></table>';
		    
		    if ( $config['use_tabs_events'] == 1 ) 
		    {
		    	// $joomleague_tabs->makeTab( 'matchinout'.$match->match_id, $inout_head, $in_out);
          $joomleague_tabs->startTab( $inout_head, 'matchinout'.$match->match_id );
          echo $in_out;
          $joomleague_tabs->endTab();
		    }
		    else {
		      echo $inout_head.'<br />'.$in_out;
		    }
		    
		    unset($came_in);
		    unset($in_out);
		  }		  
		} // in /out ends
		
		if ($config['use_tabs_events']==1) 
		{
		  // $joomleague_tabs->renderTab();
		  $joomleague_tabs->endPane();
	  }
		
	  ?>
	  </div>
	  <?php
		if ($display=='none') 
	  { 
      ?>
	      </td>
		  </tr>
		  <?php 
	  }
	}
	
	/**
	 * returns html for event formatted as list item
	 *
	 * @param Object $event
	 * @return string html code
	 */
	function getEventListItem($event)
	{
		global $database, $joomleague;

		$html = '';
		if ($event->event_sum) {
			$event->player = new Player ($database);
			$event->player->load($event->player_id);
			$html .= '<li>';
			$html .= $event->player->firstname.' '.$event->player->lastname;
			if ($event->player_id2!=0) {
			 $event->player2 = new Player ($database);
			 $event->player2->load($event->player_id2);
			 $html .= ' / '.$event->player2->firstname.' '.$event->player2->lastname;
			}
			// display event_sum if different >1
			if ($event->event_sum > 1) {
				$html .= " ($event->event_sum) ";
			}
			// display time of event if >0
			if ($event->event_time > 0) {
				$html .= ' '.$event->event_time.'\'';
				
			}
			// display event notice if exists
			if ($event->notice != '') {
                $html .= (is_numeric($event->notice)) ? ' - '.intval($event->notice) : ' - '.$event->notice;
            }
		    $html .= '</li>';
		}
		return $html;
	}

	function show_curve_form ($url_string, $selectoptions, $teamlist2options, $team, $team2, $div)
	{
	  $curveform='<form name="curveform'.$div.'" id="curveform'.$div.'" action="">'._JL_CURVE_TEAMS.'';
	  $curveform.=mosHTML::selectList( $selectoptions, 'tid_'.$div, 'class="inputbox" id="tid_'.$div.'" style="font-size:9px;"','value', 'text', $team );
	  $curveform.=mosHTML::selectList( $teamlist2options, 'tid2_'.$div, 'class="inputbox" id="tid2_'.$div.'" style="font-size:9px;"','value', 'text', $team2 );
	  $curveform.='<input type="button" style="font-size:9px;" class="inputbox" value="'._JL_CURVE_GO.'" onclick="reload_'.$div.'()" />';
	  $curveform.='</form>';
	  return $curveform;
	}

	function init_curve_js ( $platzierungen, $platzierungen2 )
	{
	  global $graphheight, $widthpermatchday, $joomleague;
		  ?>
		<center>
		<div id="fieberkurve" style="overflow: auto; position:relative;height:<?php echo $graphheight+70;?>px;width:96%;padding:0 auto 0 auto;"></div>
		</center>
		<script language="javascript" type="text/javascript">
		// <![CDATA[ 
		var g = new line_graph();
		g.setScale(1);
		<?php
		for ($x=0;$x<count($platzierungen);$x++)
		{
			$day=$x+1;
			echo "g.add('<a href=\"".sefRelToAbs(JL_COMPONENT_LINK."&func=showResultsRank&p=".$joomleague->id.JL_ITEMID_SUFFIX."&r=$day")."\">$day<\/a>', $platzierungen[$x]);\n";
		}
		for ($x=0;$x<count($platzierungen2);$x++)
		{
			$day=$x+1;
			echo "g.add_dotted('$day', $platzierungen2[$x]);\n";
		}
		echo "g.render(\"fieberkurve\", \""._JL_CURVE_X_AXIS_ROUND."\", $graphheight+20);";
		?>
		// ]]>
		</script> <?php
	}

	// baue javascript in Fieberkurve *gucky* 2007/05/06  ende
	function makemambots( $text ) {
	  global $_MAMBOTS, $database;
	  $_MAMBOTS->loadBotGroup('content');
	  $row				= new mosContent($database);
	  $params				= new mosParameters('');
	  $page				= 0;
	  $row->text			= $text;
	  $results			= $_MAMBOTS->trigger('onPrepareContent', array(&$row, &$params, $page), TRUE);
	  $results			= $_MAMBOTS->trigger('onBeforeDisplayContent', array( &$row, &$params, $page ));
	  $text				= trim(implode("\n", $results));
	  $text				.= $row->text;
	  $results			= $_MAMBOTS->trigger('onAfterDisplayContent', array( &$row, &$params, $page ));
	  $text				.= trim(implode("\n", $results));
	  return $text;
	}
	
	/**
	 * return text parsed with mambots of onPrepareContent group
	 *
	 * @param $tring $text
	 * @return string
	 */
	function printContentMambot( $text ) 
	{
	  global $_MAMBOTS;
	  $_MAMBOTS->loadBotGroup( 'content' );
	  $tmp_row = new stdClass();
	  $tmp_params = new mosParameters('');
	  $tmp_row->text = $text;
	  $_MAMBOTS->trigger( 'onPrepareContent', array( &$tmp_row, &$tmp_params ), true );
	  return $tmp_row->text;
	}
	
	function show_attendance_ranking ($a, &$config) {
	
	  global $joomleague, $colors, $type;
	
	  $favteam=explode(",", $joomleague->fav_team);
	  if (isset($_REQUEST['order'])) {
	    //reorder table according to criteria
	    switch ($_REQUEST['order']) {
	      case 'name':
	        usort( $a, array("HTML_joomleague","teamNameCmp2" ));
	        break;
	      case 'totalattend':
	        usort( $a, array("HTML_joomleague","totalattendCmp" ));
	        break;
	      case 'avgattend':
	        usort( $a, array("HTML_joomleague","avgattendCmp" ));
	        break;
	      case 'capacity':
	        usort( $a, array("HTML_joomleague","capacityCmp" ));
	        break;
	      case 'utilisation':
	        usort( $a, array("HTML_joomleague","utilisationCmp" ));
	        break;
	    }
	    if ($_REQUEST['dir']=='DESC') $a=array_reverse($a, false);
	  }
	
	  $k = 0;
	
	  for ($i=0, $n=count( $a ); $i < $n; $i++) {
	    $row = $a[$i];
	    $color = '';
	    if(in_array($a[$i]->teamid, $favteam) && $config['fav_highlight_type']==1){
	      if(trim($joomleague->fav_team_color) != "") $color = 'background-color:'.$joomleague->fav_team_color.';';
	    }
	    ?>
			<tr
				class="<?php echo ($k == 0)? 'sectiontableentry1' : 'sectiontableentry2'; ?>">
				<td style="width:6px;text-align:right;<?php echo $color;?>"><b><?php echo $i+1;?></b></td>
				<td style="width:22%;<?php echo $color;?>"><?php echo $row->team;?></td>
				<td style="width:3%;text-align:center;<?php echo $color;?>"><?php if ($row->avgspectatorspt>0) echo round($row->sumspectatorspt / $row->avgspectatorspt);else echo '-';?></td>
				<td style="width:16%;text-align:right;<?php echo $color;?>"><?php echo $row->sumspectatorspt;?></td>
				<td style="width:15%;text-align:right;<?php echo $color;?>"><?php echo round($row->avgspectatorspt,0);?></td>
				<td style="width:19%;text-align:right;<?php echo $color;?>"><?php if ($row->capacity>0) echo $row->capacity; else echo '-';?></td>
				<td style="width:20%;text-align:right;<?php echo $color;?>"><?php if ($row->capacity>0) echo round(($row->avgspectatorspt / $row->capacity)*100)."%";else echo '-';?></td>
			</tr>
			    <?php
			    $k = 1 - $k;
			
		}
	}

	/**
	 * displays basic calendar
	 * @param array matches
	 * @param array config
	 */
	function show_basic_plan(&$matches, &$teams, &$config) {
	  global $joomleague, $database, $my, $option;
	  $divLevel = intval(mosGetParam($_REQUEST, 'division', 0));
	  
	  ?>
		<table width="96%" align="center" border="0" cellpadding="3"
			cellspacing="0">
			<tr class="sectiontableheader">
			<?php
			$colspan = 6;
			if ( $config['show_events'] ) {
			  $colspan++;
			  ?>
				<td align="center" width="1%">&nbsp;</td>
				<?php
		  }
		  if ($joomleague->project_type=='DIVISIONS_LEAGUE' && isset($config['show_division']) && $config['show_division']==1) {
		    ?>
		  	<td nowrap="nowrap" valign="top" style="text-align: center">&nbsp;</td>
		  	<?php
		  	$colspan++;
		  }
		  ?>
			<td align="center"><?php echo _JL_PLAN_MATCHDAY;?></td>
			<?php
			if ($config['show_playground'] > 0 /*0= no display of playground*/)
			{
			  $colspan++;
			  echo '<td align="center">'._JL_PLAN_PLAYGROUND.'</td>';
			}
			?>
			<td align="center"><?php echo _JL_ADMIN_EDIT_MATRIX_ROUNDS_DATE;?></td>
			<?php
			if ($config['show_time']) {
			  $colspan++;
			  ?>
	  		<td align="center"><?php echo _JL_ADMIN_EDIT_MATRIX_ROUNDS_TIME;?></td>
	  		<?php
	    }
	    switch ($config['result_style']) {
        case 1 :
          ?>
          <td/>
          <td align="center" colspan="3"/>
          <td/>
          <?php
          break;        
        default :
        case 0 :
          ?>
          <td/>
          <td/>
          <td/>
          <td align="center" colspan="3"><?php echo _JL_RESULT;?></td>
          <?php
          break;
      }
			if ($config['show_referee'])
			{
			  $colspan++;
			  echo '<td align="center">'._JL_PLAN_REFEREE.'</td>';
			}
			?>
			</tr>
			<?php
		
			$user_fav_team_query="SELECT fav_team FROM #__joomleague_tip_members WHERE user_id = ".$my->id."
		      AND project_id = ".$joomleague->id;
			$joomleague->_db->setQuery($user_fav_team_query);
			$user_fav_team = $joomleague->_db->loadResult();
		
			$counter=1;
			$k = 0;
			$round_date = "";
			foreach($matches as $v) {
			  $match = new Match($database);
			  if ( !$match->bind(get_object_vars($v)) ) {
			    //$this->debug(1,$match, $v); 
			  }
			  
			  $hometeam = $teams[$match->matchpart1];
			  $home_teamtool_id = $hometeam->teamtoolid;
			  
			  $guestteam = $teams[$match->matchpart2];
			  $guest_teamtool_id = $guestteam->teamtoolid;
			  
			  $class = ($k == 0)? 'sectiontableentry1' : 'sectiontableentry2';
			  if ( $match->matchpart1 == $user_fav_team )
			  {
			    $highlight="highlight";
			  }
			  else
			  {
			    $highlight=$class;
			  }
			  if (!empty($team_plan)) $home = ($match->matchpart1 == $team_plan->id)? sprintf("%s",$hometeam->name) : $hometeam->name;
			  else $home = ($match->matchpart2)? sprintf("%s",$hometeam->name) : $hometeam->name;
			  if (!empty($team_plan)) $away = ($match->matchpart2 == $team_plan->id)? sprintf("%s",$guestteam->name) : $guestteam->name;
			  else $away = ($match->matchpart2)? sprintf("%s",$guestteam->name) : $guestteam->name;
			  $homeclub = $hometeam->club_id;
			  $awayclub = $guestteam->club_id;
			  ?>
		
			<tr class="<?php print $highlight;?>">
			<?php
		  if ($config['show_events']==1) {
		    ?>
		  	<td align="left" nowrap="nowrap" valign="top"><?php
		  	$are_there_events = $joomleague->areThereEvents ($match->match_id);
		  	if ($are_there_events > 0 || $match->match_result_detail!="") {
		  	  if ($config['use_tabs_events']) {
		    	  ?> <a href="javascript:void(0);"
		    		onclick="switchMenu('info<?php echo $match->match_id;?>');return false;"
		    		title="<?php
		          	   echo _JL_SHOW_INFO;?>"> <img
		    		src="<?php echo _JOOMLA_JL_LIVE_SITE;?>/administrator/components/com_joomleague/images/events.png"
		    		alt="<?php
		        	     echo _JL_SHOW_INFO;?>"
		    		title="<?php echo _JL_SHOW_INFO;?>" border="0" /></a> <?php
		      }
		      else {
		        ?>
		        <img
		    		src="<?php echo _JOOMLA_JL_LIVE_SITE;?>/administrator/components/com_joomleague/images/events.png"
		    		title="<?php echo $match->match_result_detail;?>" border="0" />
		        <?php
		      }
		    }
		    ?></td>
		    <?php
		  }
		  if ($joomleague->project_type=='DIVISIONS_LEAGUE' && isset($config['show_division']) && $config['show_division']==1) {
		    ?>
		  	<td nowrap="nowrap" valign="top" style="text-align: center"><?php
		  	echo $this->showDivisonRemark($hometeam, $guestteam, $config);
		  	?></td>
		  	<?php
		  }
		  ?>
				<td align="center" width="5%"><?php echo '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showResults&amp;p='.$match->project_id
				.'&amp;r='.$v->matchcode.JL_ITEMID_SUFFIX).'">'.$v->matchcode.'</a>';?></td>
				<?php
				if ($config['show_playground'] > 0 /*0= no display of playground*/) {
				  echo '<td align="center" nowrap="nowrap">';
				  $this->showPlayground($hometeam, $guestteam, $v, $config['show_playground_alert'], $config['show_playground_name'] );
				  echo '</td>';
				}
				?>
				<td align="center" nowrap="nowrap" width="10%"><?php 
				if (!strstr($match->match_date , "0000-00-00")) echo mosFormatDate($match->match_date, _JL_BASIC_CALENDAR_DATE,0);
				else echo "";
				?></td>
				<?php
				if ($config['show_time']) {
				  ?>
				<td align="center" nowrap="nowrap" width="10%"><?php 
				echo $this->format_match_time($match, $joomleague, $config);
				?></td>
				<?php
		}
		$teamA = '<td align="right" nowrap="nowrap">
		          <a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showPlan&amp;p='.$match->project_id
		                .'&amp;tid='.$match->matchpart1.JL_ITEMID_SUFFIX).'">'
		           .$home
		          .'</a>';
    if ($config['show_logo_small']) { 
      $teamA .= " ".$this->getClubIconHtml($hometeam, 1);
    }
    $teamA .= '</td>';
		
    $separator ='<td width="10" align="center">-</td>';
		
		$teamB = '<td align="left" nowrap="nowrap">';
    if ($config['show_logo_small']) { 
      $teamB .= $this->getClubIconHtml($guestteam, 1)." ";
    }
    $teamB .= '<a href="'.sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showPlan&amp;p='.$match->project_id
                    .'&amp;tid='.$match->matchpart2.JL_ITEMID_SUFFIX).'">'
               .$away
              .'</a>'
              .'</td>';
                            
		$score = '<td align="right">';
    if ($match->alt_decision==0) {
		  $e1=$match->matchpart1_result;
		  $e2=$match->matchpart2_result;
		}
		else {
		  $e1=(isset($match->matchpart1_result_decision)) ? $match->matchpart1_result_decision : 'X';
		  $e2=(isset($match->matchpart2_result_decision)) ? $match->matchpart2_result_decision : 'X';
		  $e2 .= ' <img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/court.gif" border="0" alt="'.$match->decision_info.'" title="'.$match->decision_info
	    .'" border="0" />';
		}
		$score .= sprintf('%s</td><td valign="top" width="1px">-</td><td align="left" valign="top" nowrap>%s',$e1,$e2);
		$score .= '</td>';
		
		switch ($config['result_style']) {
        case 1 :
          echo $teamA.$score.$teamB;
          break;
        default;
        case 0 :
        	echo $teamA.$separator.$teamB.$score;
        	break;
		}
		
		if ($config['show_referee'])
		{
		  ?>
			<td align="center" valign="top" nowrap="nowrap"><?php
			//echo $this->show_referee($match->referee_id, $joomleague->teams_as_referees );
			  if ($joomleague->teams_as_referees) echo $v->referee_name;
        else echo $v->referee_lastname.", ".$v->referee_firstname;
			?></td>
			<?php
    }
		?>
			</tr>
			<?php
		  if ($config['show_events']==1 && $config['use_tabs_events'] && ($are_there_events > 0 || $match->match_result_detail!="")) {
		    $config['colspan'] = $colspan;
		    $this->show_events_container_in_results($match, 'none', $config);
		  }
			$k = 1 - $k;
			$counter++;
		}
		?>
		</table>
		<?php
	}
  
	function debug($exit = true, $var = null, $var2 = null) {
		echo "<pre>";
		print_r($var);
		echo "<br/>";
		if ($var2) print_r($var2);
		echo "</pre>";
		if ($exit) exit;
	}
	
	function hiliteTeam( $name )
	{
		print '<span class="team_hilite">'.$name.'</span>';
	}
	
	/**
	 * print a game as a table row
	 *
	 * @param object game to be displayed
	 * @param format for the game date (see strftime)
	 * @param string ordered columns to display, separated with comma: DATE, VENUE, PROJECT, TEAMS, REF
	 * @param array ids of team to hiligth
	 */
	function printGameRow( $game, $columns = 'DATE, VENUE, PROJECT, TEAMS, REF', $date_format = '%A, %d %B %Y %H:%M', $hiliteTeamIds = array() )
	{
		if ( ! $game->alt_decision )
		{
      $homeScore = $game->matchpart1_result;
      $awayScore = $game->matchpart2_result;
    }
    else
    {
      $homeScore = $game->matchpart1_result_decision;
      $awayScore = $game->matchpart2_result_decision;    
    }
    ?>
		<tr class="sectiontableentry1">
		<?php 
		$cols = explode( ',', $columns );
		
		foreach ( $cols as $column )
		{
			switch ( trim( strtoupper( $column ) ) )
			{
				case 'DATE':
					?>
		      <td><?php
		      echo mosFormatDate($game->match_date, $date_format, 0)."\n";
		      ?></td>
		      <?php
					break;
				case 'VENUE':
					echo '<td nowrap="nowrap">';
		      echo $game->playgroundName;
		      echo "</td>";
	        break;
        case 'PROJECT':
          echo '<td nowrap="nowrap">';
          echo $game->projectName;
          echo "</td>";
          break;
        case 'TEAMS':
        	echo '<td nowrap="nowrap" align="right">';
		      if ( in_array( $game->homeId, $hiliteTeamIds ) ) {
		        echo $this->hiliteTeam( $game->homeName );
		      }
		      else {
		        echo $game->homeName;
		      }
		      echo "</td>";
		      echo '<td nowrap="nowrap">' . $homeScore . '</td>';
		      echo '<td nowrap="nowrap">-</td>';
		      echo '<td nowrap="nowrap">' . $awayScore . '</td>';
		      echo '<td nowrap="nowrap" align="left">';
		      if ( in_array( $game->awayId, $hiliteTeamIds ) ) {
		        echo $this->hiliteTeam( $game->awayName );
		      }
		      else {
		        echo $game->awayName;
		      }
		      echo "</td>";
        	break;
        case 'REF':
		      echo '<td nowrap="nowrap">';
		      echo $game->refereeName;
		      echo "</td>";
        	break;
			}
    }
		?>
		</tr>
		<?php
	}
	
	/**
	 * return html select list with results types (regular, overtime, shootouts)
	 *
	 * @param string $tag_name
	 * @param string $tag_attribs
	 * @param int $selected
	 * @return html
	 */
	function getResultTypeSelect($tag_name, $tag_attribs='class="inputbox" size="1"', $selected = 0)
	{
		$xrounds = array();
    $xrounds[] = mosHTML::makeOption(0, _JL_RESULTS_REGULAR);
    $xrounds[] = mosHTML::makeOption(1, _JL_RESULTS_OVERTIME);
    $xrounds[] = mosHTML::makeOption(2, _JL_RESULTS_PENALTY); 
    $mstl = mosHTML::selectList( $xrounds, $tag_name, $tag_attribs,'value', 'text', $selected );
    return $mstl;
	}
	
	/**
	 * loads joomleague.css
	 *
	 */
	function loadJLCss()
	{
		global $mainframe;
		// use a static variable to not load the css multiple times.
		static $loaded = false;
		
		if ( !$loaded ) {
			//add the css
      $mainframe->addCustomHeadTag( '<link rel="stylesheet" type="text/css" media="all" href="' . _JOOMLA_JL_LIVE_SITE.'/components/com_joomleague/css/joomleague.css'. '"/>' );   
		  $loaded = true;
		}
	}
}
